import { NextResponse, type NextRequest } from "next/server";
const SocialPostStatus = {
  DRAFT: "DRAFT",
  SCHEDULED: "SCHEDULED",
  PUBLISHED: "PUBLISHED",
  FAILED: "FAILED",
} as const;
type SocialPostStatus =
  (typeof SocialPostStatus)[keyof typeof SocialPostStatus];
import { getStaffSession } from "@/lib/staff-session";
import { socialPostsAdapter } from "@/lib/adapters/social";

export async function GET(request: NextRequest) {
  const user = await getStaffSession();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const url = new URL(request.url);
  const status = url.searchParams.get("status");
  const platform = url.searchParams.get("platform");
  const take = Number(url.searchParams.get("limit") || 50);

  const where: any = {};
  if (status) {
    where.status = status as SocialPostStatus;
  }
  if (platform) {
    where.platforms = { has: platform };
  }

  const posts = await socialPostsAdapter.findMany({
    where,
    orderBy: [{ status: "asc" }, { scheduledAt: "desc" }],
    take,
  });

  return NextResponse.json({ data: posts });
}

export async function POST(request: NextRequest) {
  const user = await getStaffSession();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await request.json();
  const {
    content,
    platforms = [],
    hashtags = [],
    link,
    mediaIds = [],
    lang = "en",
    scheduledAt,
    campaignId,
    audienceTags = [],
  } = body;

  if (!content || !platforms.length) {
    return NextResponse.json(
      { error: "content and platforms are required" },
      { status: 400 },
    );
  }

  const status: SocialPostStatus = scheduledAt
    ? SocialPostStatus.SCHEDULED
    : SocialPostStatus.DRAFT;

  const record = await socialPostsAdapter.create({
    data: {
      content,
      platforms,
      hashtags,
      link,
      mediaIds,
      lang,
      scheduledAt: scheduledAt ? new Date(scheduledAt) : null,
      status,
      campaignId,
      audienceTags,
      createdBy: user.id,
      updatedBy: user.id,
      createdAt: new Date(),
      updatedAt: new Date(),
    },
  });

  return NextResponse.json({ data: record });
}

export async function PATCH(request: NextRequest) {
  const user = await getStaffSession();
  if (!user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await request.json();
  const { id } = body;
  if (!id) {
    return NextResponse.json({ error: "id is required" }, { status: 400 });
  }

  const existing = await socialPostsAdapter.findUnique({ where: { id } });
  if (!existing) {
    return NextResponse.json(
      { error: "Social post not found" },
      { status: 404 },
    );
  }

  const record = await socialPostsAdapter.update({
    where: { id },
    data: {
      content: body.content ?? existing.content,
      platforms: Array.isArray(body.platforms)
        ? body.platforms
        : existing.platforms,
      hashtags: Array.isArray(body.hashtags)
        ? body.hashtags
        : existing.hashtags,
      link: body.link ?? existing.link,
      mediaIds: Array.isArray(body.mediaIds)
        ? body.mediaIds
        : existing.mediaIds,
      lang: body.lang ?? existing.lang,
      scheduledAt: body.scheduledAt
        ? new Date(body.scheduledAt)
        : existing.scheduledAt,
      status: body.status ?? existing.status,
      campaignId: body.campaignId ?? existing.campaignId,
      audienceTags: Array.isArray(body.audienceTags)
        ? body.audienceTags
        : existing.audienceTags,
      updatedBy: user.id,
      updatedAt: new Date(),
    },
  });

  return NextResponse.json({ data: record });
}
