import type { NavEnv } from '../../env';
import { resolveAdminBearer } from '../auth';
import { corsHeaders } from '../cors';
import { ADMIN_SESS_PREFIX, ADMIN_SESS_TTL_SEC } from '../constants';

export async function handleAuthLogin(request: Request, env: NavEnv): Promise<Response> {
  if (request.method !== 'POST') {
    return new Response('Method not allowed', { status: 405, headers: corsHeaders });
  }
  const secret = (env.ADMIN_PASSWORD || env.ADMIN_TOKEN || '').trim();
  if (!secret) {
    return new Response(JSON.stringify({ ok: false }), {
      status: 503,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  let body: { password?: unknown };
  try {
    body = await request.json();
  } catch (_) {
    return new Response(JSON.stringify({ ok: false }), {
      status: 400,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  const password = (body?.password != null ? String(body.password) : '').trim();
  if (password !== secret) {
    return new Response(JSON.stringify({ ok: false }), {
      status: 401,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  const sessionId = crypto.randomUUID();
  await env.NAV_KV.put(ADMIN_SESS_PREFIX + sessionId, '1', { expirationTtl: ADMIN_SESS_TTL_SEC });
  return new Response(JSON.stringify({ ok: true, sessionId }), {
    headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  });
}

export async function handleAuthCheck(request: Request, env: NavEnv): Promise<Response> {
  if (request.method !== 'GET') {
    return new Response('Method not allowed', { status: 405, headers: corsHeaders });
  }
  const secret = (env.ADMIN_PASSWORD || env.ADMIN_TOKEN || '').trim();
  if (!secret) {
    return new Response(JSON.stringify({ ok: false }), {
      status: 401,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  const auth = request.headers.get('Authorization');
  if (!auth || !auth.startsWith('Bearer ')) {
    return new Response(JSON.stringify({ ok: false }), {
      status: 401,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  const provided = auth.slice(7).trim();
  if (!(await resolveAdminBearer(env, provided))) {
    return new Response(JSON.stringify({ ok: false }), {
      status: 401,
      headers: { ...corsHeaders, 'Content-Type': 'application/json' },
    });
  }
  return new Response(JSON.stringify({ ok: true }), {
    headers: { ...corsHeaders, 'Content-Type': 'application/json' },
  });
}
