import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/auth/get-session-user";
import {
  getGeneratedPost,
  updateGeneratedPostCaption,
  updateGeneratedPostImageApproval,
  updateGeneratedPostStatus,
} from "@/lib/storage/generated-posts";
import type { GeneratedPostStatus } from "@/types/workflow";

export async function GET(
  _request: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const post = await getGeneratedPost(id);
  if (!post) return NextResponse.json({ error: "Post not found" }, { status: 404 });
  if (post.userId && post.userId !== user.id) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }
  return NextResponse.json({ post });
}

export async function PATCH(
  request: Request,
  { params }: { params: Promise<{ id: string }> },
) {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const existing = await getGeneratedPost(id);
  if (!existing) return NextResponse.json({ error: "Post not found" }, { status: 404 });
  if (existing.userId && existing.userId !== user.id) {
    return NextResponse.json({ error: "Forbidden" }, { status: 403 });
  }

  const body = (await request.json()) as {
    status?: GeneratedPostStatus;
    caption?: string;
    imageApproved?: boolean;
  };

  let post = null;

  if (body.caption !== undefined) {
    post = await updateGeneratedPostCaption(id, body.caption);
  } else if (body.imageApproved !== undefined) {
    post = await updateGeneratedPostImageApproval(id, body.imageApproved);
  } else if (body.status) {
    post = await updateGeneratedPostStatus(id, body.status);
  } else {
    return NextResponse.json({ error: "No valid update fields" }, { status: 400 });
  }

  if (!post) return NextResponse.json({ error: "Post not found" }, { status: 404 });
  return NextResponse.json({ success: true, post });
}
