import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/auth/get-session-user";
import { logAutoPost } from "@/lib/logging/auto-post-logger";
import { getUserProjects, saveUserProjects } from "@/lib/storage/projects";
import type { UserProjectsSnapshot } from "@/lib/storage/projects";

export async function GET() {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const snapshot = await getUserProjects(user.id, { email: user.email, name: user.name });
  return NextResponse.json({
    snapshot: snapshot ?? {
      activeProjectId: null,
      projects: [],
      dataByProjectId: {},
      updatedAt: null,
    },
  });
}

export async function PUT(request: Request) {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  try {
    const body = (await request.json()) as Partial<UserProjectsSnapshot>;
    if (!Array.isArray(body.projects) || !body.dataByProjectId) {
      return NextResponse.json({ error: "Invalid projects snapshot" }, { status: 400 });
    }

    const existing = await getUserProjects(user.id, { email: user.email, name: user.name });
    if (existing) {
      for (const project of body.projects) {
        const prev = existing.projects.find((p) => p.id === project.id);
        if (!prev || prev.status === project.status) continue;
        if (project.status === "paused") {
          await logAutoPost({
            level: "WARNING",
            event: "auto_post_paused",
            projectId: project.id,
            status: "paused",
            message: `Auto-post paused for project "${project.name}".`,
          });
        } else if (project.status === "active" && prev.status === "paused") {
          await logAutoPost({
            level: "INFO",
            event: "auto_post_resumed",
            projectId: project.id,
            status: "resumed",
            message: `Auto-post resumed for project "${project.name}".`,
          });
        }
      }
    }

    const snapshot = await saveUserProjects(
      user.id,
      {
        activeProjectId: body.activeProjectId ?? null,
        projects: body.projects,
        dataByProjectId: body.dataByProjectId,
      },
      { email: user.email, name: user.name },
    );

    return NextResponse.json({ success: true, snapshot });
  } catch (error) {
    const message = error instanceof Error ? error.message : "Save failed";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
