import { NextRequest, NextResponse } from "next/server";
import bcrypt from "bcryptjs";
import { prisma } from "@/lib/db";

function slugify(name: string): string {
  return name
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "");
}

export async function GET() {
  try {
    const config = await prisma.systemConfig.findUnique({
      where: { id: "singleton" },
    });
    return NextResponse.json({
      isSetupComplete: config?.isSetupComplete ?? false,
      setupStep: config?.setupStep ?? 0,
    });
  } catch {
    return NextResponse.json({ isSetupComplete: false, setupStep: 0 });
  }
}

export async function POST(req: NextRequest) {
  try {
    const config = await prisma.systemConfig.findUnique({
      where: { id: "singleton" },
    });

    if (config?.isSetupComplete) {
      return NextResponse.json(
        { error: "Setup is already complete" },
        { status: 400 }
      );
    }

    const body = await req.json();
    const { step, data } = body;

    if (step === 1) {
      const { email, password, displayName } = data;
      if (!email || !password || !displayName) {
        return NextResponse.json(
          { error: "All fields are required" },
          { status: 400 }
        );
      }

      const hashedPassword = await bcrypt.hash(password, 12);
      await prisma.user.create({
        data: {
          email,
          displayName,
          hashedPassword,
          role: "owner",
        },
      });

      await prisma.systemConfig.upsert({
        where: { id: "singleton" },
        update: { setupStep: 1 },
        create: { id: "singleton", setupStep: 1 },
      });

      return NextResponse.json({ success: true, nextStep: 2 });
    }

    if (step === 2) {
      const { name, type, timezone } = data;
      if (!name) {
        return NextResponse.json(
          { error: "Organization name is required" },
          { status: 400 }
        );
      }

      const owner = await prisma.user.findFirst({
        where: { role: "owner" },
      });
      if (!owner) {
        return NextResponse.json(
          { error: "Owner account not found" },
          { status: 400 }
        );
      }

      const org = await prisma.organization.create({
        data: {
          name,
          slug: slugify(name),
          type: type || "church",
          timezone: timezone || "America/Chicago",
        },
      });

      await prisma.orgMember.create({
        data: {
          userId: owner.id,
          organizationId: org.id,
          role: "owner",
        },
      });

      await prisma.systemConfig.update({
        where: { id: "singleton" },
        data: { setupStep: 2 },
      });

      return NextResponse.json({ success: true, nextStep: 3, orgId: org.id });
    }

    if (step === 3) {
      const { name, address, timezone, organizationId } = data;
      if (!name || !organizationId) {
        return NextResponse.json(
          { error: "Location name is required" },
          { status: 400 }
        );
      }

      await prisma.location.create({
        data: {
          name,
          address: address || null,
          timezone: timezone || null,
          organizationId,
        },
      });

      await prisma.systemConfig.update({
        where: { id: "singleton" },
        data: { setupStep: 3, isSetupComplete: true },
      });

      return NextResponse.json({ success: true, complete: true });
    }

    return NextResponse.json({ error: "Invalid step" }, { status: 400 });
  } catch (error) {
    console.error("[setup] Error:", error);
    return NextResponse.json(
      { error: "Setup failed" },
      { status: 500 }
    );
  }
}
