export const prerender = false;

import type { APIRoute } from 'astro';
import { isAuthenticated, ADMIN_COOKIE } from '@admin/lib/admin-auth';

interface Env { DB: D1Database }

function getCtx(locals: App.Locals) {
  const runtime = (locals as any).runtime as { env: Env } | undefined;
  return runtime?.env;
}

export const GET: APIRoute = async ({ cookies, locals }) => {
  const env = getCtx(locals);
  if (!env?.DB || !await isAuthenticated(cookies.get(ADMIN_COOKIE)?.value, env.DB)) {
    return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });
  }
  const { results } = await env.DB.prepare(
    `SELECT id, adapter_id, label, chain_id, country_code, config, interval_hours, enabled,
            last_run_at, next_run_at, created_at
       FROM source_targets
      ORDER BY adapter_id, country_code, id`
  ).all();
  return Response.json({ targets: results });
};

export const PUT: APIRoute = async ({ request, cookies, locals }) => {
  const env = getCtx(locals);
  if (!env?.DB || !await isAuthenticated(cookies.get(ADMIN_COOKIE)?.value, env.DB)) {
    return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });
  }
  const body = await request.json() as {
    id: string;
    adapter_id?: string;
    label?: string;
    chain_id?: string | null;
    country_code?: string;
    config?: string;
    interval_hours?: number;
    enabled?: number;
  };
  if (!body.id) return Response.json({ error: 'id required' }, { status: 400 });
  if (body.country_code !== undefined && !/^[A-Z]{2}$/.test(body.country_code.trim().toUpperCase())) {
    return Response.json({ error: 'country_code must be ISO-2 uppercase (e.g. LB)' }, { status: 400 });
  }

  // Validate config JSON if provided
  if (body.config !== undefined) {
    try { JSON.parse(body.config); } catch {
      return Response.json({ error: 'config must be valid JSON' }, { status: 400 });
    }
  }

  await env.DB.prepare(
    `UPDATE source_targets
        SET adapter_id     = COALESCE(?, adapter_id),
            label          = COALESCE(?, label),
            chain_id       = CASE WHEN ? = 1 THEN NULLIF(?, '') ELSE chain_id END,
            country_code   = COALESCE(?, country_code),
            config         = COALESCE(?, config),
            interval_hours = COALESCE(?, interval_hours),
            enabled        = COALESCE(?, enabled)
       WHERE id = ?`
  ).bind(
    body.adapter_id ?? null,
    body.label ?? null,
    body.chain_id === undefined ? 0 : 1,
    body.chain_id ?? '',
    body.country_code?.trim().toUpperCase() ?? null,
    body.config ?? null,
    body.interval_hours ?? null,
    body.enabled ?? null,
    body.id
  ).run();

  return Response.json({ ok: true });
};

export const POST: APIRoute = async ({ request, cookies, locals }) => {
  const env = getCtx(locals);
  if (!env?.DB || !await isAuthenticated(cookies.get(ADMIN_COOKIE)?.value, env.DB)) {
    return new Response(JSON.stringify({ error: 'Unauthorized' }), { status: 401 });
  }

  const body = await request.json() as {
    id?: string;
    adapter_id?: string;
    label?: string;
    chain_id?: string | null;
    country_code?: string;
    config?: string;
    interval_hours?: number;
    enabled?: number;
  };

  if (!body.id || !body.adapter_id || !body.label || !body.country_code) {
    return Response.json({ error: 'id, adapter_id, label, and country_code are required' }, { status: 400 });
  }
  const countryCode = body.country_code.trim().toUpperCase();
  if (!/^[A-Z]{2}$/.test(countryCode)) {
    return Response.json({ error: 'country_code must be ISO-2 uppercase (e.g. LB)' }, { status: 400 });
  }

  const config = body.config ?? '{}';
  try { JSON.parse(config); } catch {
    return Response.json({ error: 'config must be valid JSON' }, { status: 400 });
  }

  const intervalHours = Number.isFinite(body.interval_hours) && (body.interval_hours ?? 0) > 0
    ? Math.floor(body.interval_hours as number)
    : 2;
  const enabled = body.enabled === 0 ? 0 : 1;

  try {
    await env.DB.prepare(
      `INSERT INTO source_targets
         (id, adapter_id, label, chain_id, country_code, config, interval_hours, enabled, next_run_at)
       VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL)`
    ).bind(
      body.id.trim(),
      body.adapter_id.trim(),
      body.label.trim(),
      body.chain_id || null,
      countryCode,
      config,
      intervalHours,
      enabled
    ).run();
    return Response.json({ ok: true });
  } catch (err) {
    return Response.json({ error: String(err) }, { status: 409 });
  }
};
