import type { APIRoute } from 'astro';
import { requireApiToken } from '../../../lib/apiAuth';
import { isAdminAuthenticated } from '../../../lib/adminAuth';
import { runTassAgent } from '../../../lib/tassAgent';

export const POST: APIRoute = async (context) => {
  if (!isAdminAuthenticated(context)) {
    const unauthorized = requireApiToken(context);

    if (unauthorized) {
      return unauthorized;
    }
  }

  try {
    const contentType = context.request.headers.get('content-type') ?? '';
    const payload = contentType.includes('application/json') ? await context.request.json() : {};
    const limit = Math.min(Math.max(Number(payload.limit ?? 3), 1), 10);
    const result = await runTassAgent(limit);

    return new Response(JSON.stringify({ ok: true, ...result }), {
      headers: { 'content-type': 'application/json; charset=utf-8' },
    });
  } catch (error) {
    return new Response(JSON.stringify({ ok: false, error: error instanceof Error ? error.message : 'Agent failed' }), {
      status: 500,
      headers: { 'content-type': 'application/json; charset=utf-8' },
    });
  }
};
