import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { sendInvitationEmail } from "@/lib/email-sender";
import {
  requireApiAuthWithOrg,
  requireApiAuthWithPermission,
  handleApiError,
} from "@/lib/api-auth";

export async function GET() {
  try {
    const session = await requireApiAuthWithOrg("users.view");

    const invitations = await prisma.invitation.findMany({
      where: { organizationId: session.user.orgId, acceptedAt: null },
      orderBy: { createdAt: "desc" },
      select: {
        id: true,
        email: true,
        role: true,
        expiresAt: true,
        acceptedAt: true,
      },
    });

    return NextResponse.json({ invitations });
  } catch (error) {
    return handleApiError(error);
  }
}

export async function POST(req: NextRequest) {
  try {
    const session = await requireApiAuthWithPermission("users.invite");

    const { email, role } = await req.json();

    if (!email) {
      return NextResponse.json(
        { error: "Email is required" },
        { status: 400 }
      );
    }

    const existing = await prisma.invitation.findFirst({
      where: {
        email,
        organizationId: session.user.orgId,
        acceptedAt: null,
        expiresAt: { gt: new Date() },
      },
    });

    if (existing) {
      return NextResponse.json(
        { error: "An active invitation already exists for this email" },
        { status: 409 }
      );
    }

    const existingMember = await prisma.orgMember.findFirst({
      where: {
        organizationId: session.user.orgId,
        user: { email },
      },
    });

    if (existingMember) {
      return NextResponse.json(
        { error: "This person is already a member" },
        { status: 409 }
      );
    }

    const expiresAt = new Date();
    expiresAt.setDate(expiresAt.getDate() + 7);

    const invitation = await prisma.invitation.create({
      data: {
        email,
        role: role || "viewer",
        organizationId: session.user.orgId,
        invitedById: session.user.id,
        expiresAt,
      },
    });

    try {
      const baseUrl = new URL(req.url).origin;
      const orgName = session.user.orgName || "the organization";
      const inviterName = session.user.displayName || session.user.name || undefined;
      await sendInvitationEmail(email, baseUrl, invitation.token, orgName, inviterName);
    } catch (emailErr) {
      console.warn("[org/invitations] Invitation email failed (non-blocking):", emailErr);
    }

    return NextResponse.json({ success: true });
  } catch (error) {
    return handleApiError(error);
  }
}
