import { NextResponse } from "next/server";
import { getSessionUser } from "@/lib/auth/get-session-user";
import { getUserProjects } from "@/lib/storage/projects";
import type { BrandProfile, BusinessContext, Project } from "@/types/workflow";
import { resolveWebsiteIntelligence, scrapeWebsite } from "@/lib/context/website-intelligence";
import { buildBusinessContext, suggestBrandFromWebsite } from "@/lib/context/business-context";

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

  try {
    const body = (await request.json()) as {
      url?: string;
      projectId?: string;
      project?: Project;
      brand?: BrandProfile;
      businessContext?: BusinessContext | null;
      forceRefresh?: boolean;
    };

    const url = body.url?.trim() || body.project?.website?.trim();
    if (!url) {
      return NextResponse.json({ error: "Website URL is required." }, { status: 400 });
    }

    if (body.projectId) {
      const snapshot = await getUserProjects(user.id);
      const owned = snapshot?.projects.some((p) => p.id === body.projectId);
      if (!owned) {
        return NextResponse.json({ error: "Project not found." }, { status: 404 });
      }
    }

    const project: Project = body.project ?? {
      id: body.projectId ?? "temp",
      name: "",
      website: url,
      industry: "",
      timezone: "",
      countries: [],
      status: "active",
      createdAt: "",
      updatedAt: "",
    };

    const brand: BrandProfile = body.brand ?? {
      companyName: "",
      tagline: "",
      industry: "",
      brandVoice: "Professional",
      logoDataUrl: null,
      logoFileName: null,
    };

    const website = body.projectId
      ? await resolveWebsiteIntelligence(body.projectId, { ...project, website: url }, brand, {
          forceRefresh: body.forceRefresh ?? true,
        })
      : await scrapeWebsite(url);

    const businessContext = buildBusinessContext({
      project: { ...project, website: url },
      brand,
      website,
      existing: body.businessContext,
    });

    return NextResponse.json({
      website,
      businessContext,
      brandSuggestions: suggestBrandFromWebsite(brand, website),
    });
  } catch (err) {
    const message = err instanceof Error ? err.message : "Website analysis failed";
    return NextResponse.json({ error: message }, { status: 500 });
  }
}
