import { getBrandProfile, importBrandGuidelines, importBrandLogo, updateBrandProfile } from '@/lib/brand.js';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

const HEX_COLOR = /^#[0-9A-F]{3,8}$/;
const LOGO_EXTENSIONS = new Set(['.svg', '.png', '.jpg', '.jpeg', '.webp']);
const GUIDELINES_EXTENSIONS = new Set(['.html', '.htm', '.md', '.txt', '.css', '.svg', '.pdf']);

function capList(list, limit = 30) {
  return list.slice(0, limit).map(item => item.slice(0, 120));
}

function parseList(value) {
  if (Array.isArray(value)) return capList(value.map(v => String(v).trim()).filter(Boolean));
  return capList(String(value || '').split(/\r?\n|,/).map(v => v.trim()).filter(Boolean));
}

function parseColors(value) {
  if (Array.isArray(value)) {
    return value
      .map(c => ({ name: String(c.name || '').trim().slice(0, 80), value: String(c.value || '').trim().toUpperCase() }))
      .filter(c => HEX_COLOR.test(c.value))
      .slice(0, 30);
  }
  return String(value || '').split(/\r?\n/).map((line, idx) => {
    const [name, rawValue] = line.includes(':') ? line.split(':') : [`Color ${idx + 1}`, line];
    return { name: name.trim().slice(0, 80), value: rawValue.trim().toUpperCase() };
  }).filter(c => HEX_COLOR.test(c.value)).slice(0, 30);
}

function uploadError(kind, file) {
  if (!['logo', 'guidelines'].includes(kind)) return new Response('kind must be logo or guidelines', { status: 400 });
  const name = String(file?.name || '');
  const ext = name.toLowerCase().match(/\.[a-z0-9]+$/)?.[0] || '';
  const maxBytes = kind === 'logo' ? 1_000_000 : 2_000_000;
  if (Number(file?.size || 0) > maxBytes) return new Response('file too large', { status: 413 });
  if (kind === 'logo' && !LOGO_EXTENSIONS.has(ext)) return new Response('unsupported logo format', { status: 400 });
  if (kind === 'guidelines' && !GUIDELINES_EXTENSIONS.has(ext)) return new Response('unsupported guidelines format', { status: 400 });
  return null;
}

export async function GET() {
  return Response.json({ brand: getBrandProfile() });
}

export async function PUT(req) {
  let body;
  try {
    body = await req.json();
  } catch {
    return new Response('Invalid JSON', { status: 400 });
  }

  const next = {};
  if (body.active !== undefined) next.active = Boolean(body.active);
  if (body.company_name !== undefined) next.company_name = String(body.company_name).trim().slice(0, 120);
  if (body.tagline !== undefined) next.tagline = String(body.tagline).trim().slice(0, 240);
  if (body.presentation_style !== undefined) next.presentation_style = String(body.presentation_style).trim().slice(0, 2000);
  if (body.document_types !== undefined) next.document_types = parseList(body.document_types);
  if (body.fonts !== undefined) next.fonts = parseList(body.fonts);
  if (body.voice !== undefined) next.voice = parseList(body.voice);
  if (body.colors !== undefined) next.colors = parseColors(body.colors);

  return Response.json({ ok: true, brand: updateBrandProfile(next) });
}

export async function POST(req) {
  let form;
  try {
    form = await req.formData();
  } catch {
    return new Response('Invalid form data', { status: 400 });
  }
  const kind = String(form.get('kind') || 'guidelines');
  const file = form.get('file');
  if (!file || typeof file === 'string') {
    return new Response('file is required', { status: 400 });
  }
  const error = uploadError(kind, file);
  if (error) return error;
  if (kind === 'logo') {
    return Response.json({ ok: true, brand: await importBrandLogo(file) });
  }
  return Response.json({ ok: true, brand: await importBrandGuidelines(file) });
}
