import { NextRequest, NextResponse } from 'next/server';
import { dbHelpers } from '@/lib/db';
import { getSession } from '@/lib/auth';
import { migrationNotifyEnqueueSchema } from '@/lib/validators';
import { buildOutboxInserts } from '@/lib/migration-notifications';

async function authorizeProject(request: NextRequest, projectId: string) {
  const accessToken = request.cookies.get('scriba.access_token')?.value;
  const session = await getSession(accessToken);
  if (!session) {
    return { error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) };
  }
  const project = await dbHelpers.getProject(projectId);
  if (!project) {
    return { error: NextResponse.json({ error: 'Conversion not found' }, { status: 404 }) };
  }
  if (project.userId !== session.user.id) {
    return { error: NextResponse.json({ error: 'Forbidden' }, { status: 403 }) };
  }
  return { session, project };
}

export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const { id: projectId } = await params;
    const auth = await authorizeProject(request, projectId);
    if ('error' in auth) return auth.error;

    const body = await request.json().catch(() => null);
    if (!body) {
      return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
    }
    const parsed = migrationNotifyEnqueueSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json({ error: parsed.error.issues[0]?.message ?? 'Invalid input' }, { status: 400 });
    }

    const { project, session } = auth;
    const rawConfig = project.config;
    const config =
      rawConfig && typeof rawConfig === 'object' && !Array.isArray(rawConfig)
        ? (rawConfig as Record<string, unknown>)
        : {};

    const rows = buildOutboxInserts(
      session.user.id,
      projectId,
      project.name ?? 'Project',
      config,
      parsed.data.event,
      parsed.data.detail,
    );

    const queued = await dbHelpers.insertNotificationOutboxBatch(rows);

    if (queued > 0) {
      await dbHelpers.addActivity(
        projectId,
        `Queued ${queued} notification(s) for ${parsed.data.event} (${rows.map((r) => r.channel).join(', ')})`,
        'Pending delivery (configure SMTP / workers when ready)',
        'System',
      );
    }

    return NextResponse.json({ success: true, queued });
  } catch (error) {
    console.error('notification enqueue:', error);
    return NextResponse.json({ error: 'Failed to enqueue notifications' }, { status: 500 });
  }
}
