/**
 * PUT    /api/email-reports/schedules/[id] — update a schedule
 * DELETE /api/email-reports/schedules/[id] — delete a schedule
 */

import { NextResponse } from "next/server";
import { getCurrentUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { computeNextSendAt } from "@/lib/services/email-sender";

export const dynamic = "force-dynamic";

async function resolve(id: string, userId: string) {
  const schedule = await prisma.emailReportSchedule.findUnique({
    where: { id },
    include: { brand: { include: { organization: { include: { memberships: true } } } } },
  });
  if (!schedule) return { error: "Not found" as const, status: 404 };
  if (!schedule.brand.organization.memberships.some((m) => m.userId === userId)) {
    return { error: "Access denied" as const, status: 403 };
  }
  return { schedule };
}

export async function PUT(req: Request, { params }: { params: { id: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const resolved = await resolve(params.id, user.id);
  if ("error" in resolved) return NextResponse.json({ error: resolved.error }, { status: resolved.status });

  const body = await req.json().catch(() => ({})) as Record<string, unknown>;
  const existing = resolved.schedule;

  const frequency = typeof body.frequency === "string" ? body.frequency : existing.frequency;
  const timeOfDay = typeof body.timeOfDay === "string" ? body.timeOfDay : existing.timeOfDay;
  const dayOfWeek = typeof body.dayOfWeek === "number" ? body.dayOfWeek : existing.dayOfWeek;
  const dayOfMonth = typeof body.dayOfMonth === "number" ? body.dayOfMonth : existing.dayOfMonth;

  const updated = await prisma.emailReportSchedule.update({
    where: { id: params.id },
    data: {
      name: typeof body.name === "string" ? body.name : undefined,
      frequency,
      dayOfWeek,
      dayOfMonth,
      timeOfDay,
      recipients: Array.isArray(body.recipients) ? body.recipients as string[] : undefined,
      sections: Array.isArray(body.sections) ? body.sections as string[] : undefined,
      includeAiAnalysis: typeof body.includeAiAnalysis === "boolean" ? body.includeAiAnalysis : undefined,
      includeCompetitorScan: typeof body.includeCompetitorScan === "boolean" ? body.includeCompetitorScan : undefined,
      includeMarketInsights: typeof body.includeMarketInsights === "boolean" ? body.includeMarketInsights : undefined,
      isActive: typeof body.isActive === "boolean" ? body.isActive : undefined,
      nextSendAt: computeNextSendAt(frequency, timeOfDay, dayOfWeek, dayOfMonth),
    },
  });

  return NextResponse.json({ schedule: updated });
}

export async function DELETE(_req: Request, { params }: { params: { id: string } }) {
  const user = await getCurrentUser();
  if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });

  const resolved = await resolve(params.id, user.id);
  if ("error" in resolved) return NextResponse.json({ error: resolved.error }, { status: resolved.status });

  await prisma.emailReportSchedule.delete({ where: { id: params.id } });
  return NextResponse.json({ ok: true });
}
