import { NextRequest, NextResponse } from 'next/server';
import { dbHelpers } from '@/lib/db';
import { getSession } from '@/lib/auth';
import { updateProjectSchema } from '@/lib/validators';
import {
  applyMarkersToProjectPayloadConfig,
  buildMarkerMetadata,
} from '@/lib/export-bundle';

/** Verify session + project ownership. Returns { session, project } or an error Response. */
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 }) };
  }

  // Ownership check: only the conversion owner may access it
  if (project.userId !== session.user.id) {
    return { error: NextResponse.json({ error: 'Forbidden' }, { status: 403 }) };
  }

  return { session, project };
}

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

    const { project } = auth;

    // Parse JSON fields (PostgreSQL returns JSONB as objects, but we normalize)
    const parsedProject = {
      ...project,
      tags: Array.isArray(project.tags) ? project.tags : JSON.parse(project.tags || '[]'),
      team: Array.isArray(project.team) ? project.team : JSON.parse(project.team || '[]'),
      activity: Array.isArray(project.activity) ? project.activity : JSON.parse(project.activity || '[]'),
    };

    parsedProject.config = applyMarkersToProjectPayloadConfig(
      (parsedProject.config ?? {}) as Record<string, unknown>,
      buildMarkerMetadata(parsedProject)
    );
    
    return NextResponse.json({ conversion: parsedProject, project: parsedProject });
  } catch (error) {
    console.error('Error fetching conversion:', error);
    return NextResponse.json({ error: 'Failed to fetch conversion' }, { status: 500 });
  }
}

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

    const body = await request.json();
    const parsed = updateProjectSchema.safeParse(body);
    if (!parsed.success) {
      return NextResponse.json({ error: parsed.error.issues[0]?.message ?? 'Input non valido' }, { status: 400 });
    }

    // Merge config: new keys are added/overwritten but existing keys are preserved.
    // If DB `config` is null, still shallow-merge so wizard fields (e.g. customRules) are not wiped.
    const updates = { ...parsed.data };
    if (updates.config) {
      const prev =
        auth.project.config && typeof auth.project.config === 'object' && !Array.isArray(auth.project.config)
          ? (auth.project.config as Record<string, unknown>)
          : {};
      updates.config = { ...prev, ...updates.config };
    }

    const updatedProject = await dbHelpers.updateProjectProgress(id, updates);
    return NextResponse.json({ success: true, conversion: updatedProject, project: updatedProject });
  } catch (error) {
    console.error('Error updating conversion:', error);
    return NextResponse.json({ error: 'Failed to update conversion' }, { status: 500 });
  }
}

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

    await dbHelpers.deleteProject(id);
    
    return NextResponse.json({ success: true, message: 'Conversion deleted' });
  } catch (error) {
    console.error('Error deleting conversion:', error);
    return NextResponse.json({ error: 'Failed to delete conversion' }, { status: 500 });
  }
}
