import { NextResponse } from "next/server";
import { z } from "zod";
import { getSession } from "@/lib/auth/session";
import { db } from "@/lib/db";
import { getEnv } from "@/lib/env";
import { pairSite } from "@/lib/site-agent/pairing";

const inputSchema = z.object({
  name: z.string().trim().min(1).max(100),
  url: z.string().trim().url(),
  code: z.string().regex(/^[a-f0-9]{64}$/),
  environment: z.enum(["Production", "Staging", "Development"]),
  profile: z.enum(["read_only", "standard"]),
});

export async function GET() {
  const session = await getSession();
  return NextResponse.json({ authenticated: Boolean(session) }, { status: session ? 200 : 401 });
}

export async function POST(request: Request) {
  const session = await getSession();
  if (!session) return NextResponse.json({ message: "Sign in with your WooCommerce account to connect the site." }, { status: 401 });
  const origin = request.headers.get("origin");
  if (origin && origin !== new URL(getEnv().APP_URL).origin) {
    return NextResponse.json({ message: "Invalid request origin." }, { status: 403 });
  }
  const membership = await db.organizationMember.findFirst({ where: { userId: session.userId }, orderBy: { createdAt: "asc" } });
  if (!membership) return NextResponse.json({ message: "No workspace is available for this account." }, { status: 403 });
  const parsed = inputSchema.safeParse(await request.json().catch(() => null));
  if (!parsed.success) return NextResponse.json({ message: "Complete the site, environment and permission fields." }, { status: 400 });

  try {
    const site = await pairSite({ ...parsed.data, organizationId: membership.organizationId, actorUserId: session.userId });
    return NextResponse.json({ site }, { status: 201, headers: { "Cache-Control": "no-store" } });
  } catch (error) {
    const message = error instanceof Error ? error.message : "The site could not be connected.";
    return NextResponse.json({ message }, { status: message.includes("already enrolled") || message.includes("site limit") ? 409 : 422 });
  }
}
