import { NextResponse } from 'next/server';
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { documents, clients, DocumentSigner } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
import { createSigningToken } from '@/lib/signing/token';
import { sendSigningRequestEmail } from '@/lib/signing/signing-mailer';
import { logAuditEvent } from '@/lib/signing/audit';

export async function POST(
  _req: Request,
  { params }: { params: Promise<{ id: string }> }
) {
  const session = await auth();
  if (!session) return new Response('Unauthorized', { status: 401 });

  const { id } = await params;

  try {
    const doc = await db.query.documents.findFirst({
      where: eq(documents.id, id),
    });
    if (!doc) return NextResponse.json({ error: 'Document not found' }, { status: 404 });
    if (!doc.preparedFilePath)
      return NextResponse.json({ error: 'Document not yet prepared' }, { status: 422 });
    if (doc.status === 'Signed')
      return NextResponse.json({ error: 'Already signed' }, { status: 409 });

    const baseUrl = process.env.APP_BASE_URL ?? 'http://localhost:3000';

    if (doc.signers && (doc.signers as DocumentSigner[]).length > 0) {
      // ── Multi-signer path (D-02) ──
      const signers = doc.signers as DocumentSigner[];
      await Promise.all(
        signers.map(async (signer) => {
          const { token, expiresAt } = await createSigningToken(doc.id, signer.email);
          const signingUrl = `${baseUrl}/sign/${token}`;
          await sendSigningRequestEmail({
            to: signer.email,
            documentName: doc.name,
            signingUrl,
            expiresAt,
          });
          await logAuditEvent({
            documentId: doc.id,
            eventType: 'email_sent',
            metadata: { signerEmail: signer.email },
          });
        })
      );
    } else {
      // ── Legacy single-signer path (D-01) ──
      const clientId = doc.assignedClientId ?? doc.clientId;
      const client = await db.query.clients.findFirst({ where: eq(clients.id, clientId) });
      if (!client) return NextResponse.json({ error: 'Client not found' }, { status: 422 });

      const { token, expiresAt } = await createSigningToken(doc.id);
      const signingUrl = `${baseUrl}/sign/${token}`;
      await sendSigningRequestEmail({
        to: client.email,
        clientName: client.name,
        documentName: doc.name,
        signingUrl,
        expiresAt,
      });
      await logAuditEvent({ documentId: doc.id, eventType: 'email_sent' });
    }

    // Update status to Sent (skip if already Sent or Signed to avoid downgrade)
    if (doc.status === 'Draft') {
      await db
        .update(documents)
        .set({ status: 'Sent', sentAt: new Date() })
        .where(eq(documents.id, id));
    }

    return NextResponse.json({ ok: true });
  } catch (err) {
    console.error('[send] error:', err);
    return NextResponse.json({ error: 'Failed to send signing email' }, { status: 502 });
  }
}
