import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { z } from "zod";

const documentVisibilitySchema = z.object({
  siret:      z.boolean().optional(),
  vatNumber:  z.boolean().optional(),
  ninea:      z.boolean().optional(),
  rccm:       z.boolean().optional(),
  phone:      z.boolean().optional(),
  email:      z.boolean().optional(),
  website:    z.boolean().optional(),
  address:    z.boolean().optional(),
});

const updateSchema = z.object({
  name:                z.string().min(2, "Nom requis"),
  email:               z.string().email().optional().or(z.literal("")),
  phone:               z.string().optional(),
  address:             z.string().optional(),
  city:                z.string().optional(),
  postalCode:          z.string().optional(),
  country:             z.string().optional(),
  siret:               z.string().optional(),
  vatNumber:           z.string().optional(),
  ninea:               z.string().optional(),
  rccm:                z.string().optional(),
  currency:            z.string().optional(),
  website:             z.string().optional(),
  documentVisibility:  documentVisibilitySchema.optional(),
});

export async function GET() {
  const ctx = await getSessionContext();
  if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié" }, { status: 401 });

  const membership = await prisma.organizationMember.findFirst({
    where: { userId: ctx.userId, joinedAt: { not: null } },
    include: {
      organization: {
        include: {
          subscription: true,
          members: { include: { user: { select: { id: true, name: true, email: true, image: true } } } },
        },
      },
    },
    orderBy: { createdAt: "asc" },
  });

  if (!membership) {
    return NextResponse.json({ success: false, error: "Aucune organisation trouvée" }, { status: 404 });
  }

  return NextResponse.json({ success: true, data: membership.organization });
}

export async function PATCH(req: NextRequest) {
  try {
    const ctx = await getSessionContext();
    if (!ctx) return NextResponse.json({ success: false, error: "Non authentifié" }, { status: 401 });

    const membership = await prisma.organizationMember.findFirst({
      where: { userId: ctx.userId, joinedAt: { not: null } },
      select: { organizationId: true, role: true },
      orderBy: { createdAt: "asc" },
    });

    if (!membership) {
      return NextResponse.json({ success: false, error: "Organisation introuvable" }, { status: 404 });
    }

    if (!["OWNER", "ADMIN", "SUPER_ADMIN"].includes(membership.role)) {
      return NextResponse.json({ success: false, error: "Permissions insuffisantes" }, { status: 403 });
    }

    const body = await req.json().catch(() => null);
    if (!body) return NextResponse.json({ success: false, error: "Corps invalide" }, { status: 400 });

    const parsed = updateSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json({ success: false, error: "Données invalides", details: parsed.error.flatten() }, { status: 400 });
    }

    const data = Object.fromEntries(
      Object.entries(parsed.data).map(([k, v]) => [k, v === "" ? null : v])
    ) as Record<string, any>;

    const updated = await prisma.organization.update({
      where: { id: membership.organizationId },
      data,
    });

    return NextResponse.json({ success: true, data: updated });
  } catch (err: any) {
    console.error("[PATCH /api/organizations/current]", err);
    return NextResponse.json({ success: false, error: "Erreur serveur", detail: err?.message }, { status: 500 });
  }
}
