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

export async function POST(
  req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await requireApiAuthWithPermission("users.invite");
    const { id } = await params;

    const invitation = await prisma.invitation.findFirst({
      where: { id, organizationId: session.user.orgId },
    });

    if (!invitation) {
      return NextResponse.json({ error: "Invitation not found" }, { status: 404 });
    }

    if (invitation.acceptedAt) {
      return NextResponse.json(
        { error: "This invitation has already been accepted" },
        { status: 400 }
      );
    }

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

    await prisma.invitation.update({
      where: { id },
      data: { expiresAt: newExpiry },
    });

    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(invitation.email, baseUrl, invitation.token, orgName, inviterName);

    return NextResponse.json({ success: true, message: "Invitation resent" });
  } catch (error) {
    return handleApiError(error);
  }
}

export async function DELETE(
  _req: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const session = await requireApiAuthWithPermission("users.invite");
    const { id } = await params;

    const invitation = await prisma.invitation.findFirst({
      where: { id, organizationId: session.user.orgId },
    });

    if (!invitation) {
      return NextResponse.json({ error: "Invitation not found" }, { status: 404 });
    }

    await prisma.invitation.delete({ where: { id } });

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