import { NextRequest, NextResponse } from 'next/server';
import { requireApiAuth } from '@/lib/auth';
import { prisma } from '@/lib/prisma';
import { googleSheetsImportSchema } from '@/lib/validation';
import { buildGoogleSheetsCsvUrl, normalizeRows, parseCsvText, processImport } from '@/lib/import-utils';

export async function POST(request: NextRequest) {
  const authError = await requireApiAuth(request);
  if (authError) return authError;

  let body: unknown;
  try {
    body = await request.json();
  } catch {
    return NextResponse.json({ error: 'JSON inválido' }, { status: 400 });
  }

  const parsed = googleSheetsImportSchema.safeParse(body);
  if (!parsed.success) {
    return NextResponse.json({ error: parsed.error.issues[0]?.message || 'Datos inválidos' }, { status: 400 });
  }

  try {
    const csvUrl = buildGoogleSheetsCsvUrl(parsed.data.url, parsed.data.gid);

    const response = await fetch(csvUrl, {
      method: 'GET',
      cache: 'no-store'
    });

    if (!response.ok) {
      return NextResponse.json(
        {
          error: `No se pudo leer Google Sheets (status ${response.status}). Verifica que esté publicado o compartido públicamente.`
        },
        { status: 400 }
      );
    }

    const text = await response.text();
    if (!text.trim()) {
      return NextResponse.json({ error: 'La hoja está vacía' }, { status: 400 });
    }

    if (text.trimStart().startsWith('<!DOCTYPE html') || text.trimStart().startsWith('<html')) {
      return NextResponse.json(
        {
          error:
            'La hoja no devolvió CSV. Publica la hoja como CSV (Archivo > Compartir > Publicar en la Web) y vuelve a intentar.'
        },
        { status: 400 }
      );
    }

    const records = parseCsvText(text);
    const rows = normalizeRows(records);
    const summary = await processImport(prisma, rows, parsed.data.mode);

    return NextResponse.json({
      ...summary,
      sourceUrl: csvUrl
    });
  } catch (error) {
    return NextResponse.json(
      {
        error: error instanceof Error ? error.message : 'No se pudo sincronizar desde Google Sheets'
      },
      { status: 400 }
    );
  }
}
