import type { APIRoute } from 'astro';
import { env } from 'cloudflare:workers';
import { sql } from 'drizzle-orm';
import type { Querier } from '@platform-modules/db';
import { applySettingsSchema, applyStorefrontSchema } from '../../lib/install.js';
import { buildAuthEngine, type AuthEnv } from '../../lib/auth-engine.js';
import { getDb } from '../../lib/db.js';
import { jsonError } from '../../lib/http.js';
import { claimInstall, claimInstallOnce } from '../../lib/settings.js';
import { setSession, type SessionEnv } from '../../lib/session.js';

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

export const prerender = false;

export const POST: APIRoute = async ({ request, cookies, redirect }) => {
  const cfEnv = env as (AuthEnv & SessionEnv) | undefined;
  if (!cfEnv?.DB && !cfEnv?.DATABASE_URL) {
    return jsonError(503, 'service_unavailable', 'Database is not configured.');
  }

  const form = await request.formData();
  const csrf = String(form.get('csrf') ?? '');
  const cookieToken = cookies.get('install_csrf')?.value ?? '';
  if (!cookieToken || cookieToken !== csrf) {
    return jsonError(403, 'forbidden', 'Invalid request.');
  }

  const storeName = String(form.get('storeName') ?? '').trim();
  const tagline = String(form.get('tagline') ?? '').trim();
  const currency = String(form.get('currency') ?? '').trim();
  const locale = String(form.get('locale') ?? '').trim();
  const themeMode = String(form.get('themeMode') ?? 'system').trim();
  const email = String(form.get('email') ?? '').trim().toLowerCase();
  const password = String(form.get('password') ?? '');
  const confirmPassword = String(form.get('confirmPassword') ?? '');
  const stripePublishableKey = String(form.get('stripePublishableKey') ?? '').trim();
  const testMode = form.get('testMode') === 'on' || form.get('testMode') === 'true';
  const priceMode = form.get('priceMode') === 'inclusive' ? 'inclusive' : 'exclusive';

  if (!storeName) {
    return jsonError(400, 'validation_error', 'Store name is required.');
  }
  if (!EMAIL_RE.test(email)) {
    return jsonError(400, 'validation_error', 'A valid admin email is required.');
  }
  if (password.length < 8) {
    return jsonError(400, 'validation_error', 'Password must be at least 8 characters.');
  }
  if (password !== confirmPassword) {
    return jsonError(400, 'validation_error', 'Passwords do not match.');
  }

  const { db } = getDb(cfEnv);

  const authSecret = (cfEnv as Record<string, unknown>)?.AUTH_SECRET;
  if (typeof authSecret !== 'string' || authSecret.trim().length < 16) {
    return jsonError(503, 'service_unavailable', 'Service temporarily unavailable.');
  }

  await applySettingsSchema(db as unknown as Querier);
  const claimed = await claimInstallOnce(db as unknown as Querier);
  if (!claimed) {
    return jsonError(409, 'already_installed', 'Store is already installed.');
  }

  let createdUserId: string | undefined;
  try {
    await applyStorefrontSchema(db);

    const { userId } = await buildAuthEngine(cfEnv).createUser({
      email,
      password,
      roles: ['owner'],
    });
    createdUserId = userId;

    await claimInstall(db as unknown as Querier, {
      storeName,
      currency: currency || 'USD',
      locale: locale || 'en',
      tagline: tagline || undefined,
      themeMode: themeMode || 'system',
      priceMode: priceMode as 'inclusive' | 'exclusive',
      stripePublishableKey: stripePublishableKey || undefined,
      stripeTestMode: testMode,
    });
  } catch (e) {
    const isUniqueError =
      createdUserId === undefined &&
      ((e instanceof Error &&
        (e.message.includes('UNIQUE') ||
          e.message.toLowerCase().includes('duplicate'))) ||
        (typeof (e as Record<string, unknown>).code === 'string' &&
          (e as Record<string, unknown>).code === '23505'));
    if (isUniqueError) {
      try {
        await (db as unknown as Querier).execute(
          sql`DELETE FROM mod_storefront_settings WHERE id = 'installed' AND value = 'pending'`,
        );
      } catch {
        // Cleanup failed — swallow inner error
      }
      return jsonError(409, 'email_taken', 'An account with that email address already exists.');
    }
    if (createdUserId) {
      try {
        await (db as unknown as Querier).execute(
          sql`DELETE FROM auth_users WHERE id = ${createdUserId}`,
        );
      } catch {
        // Orphan cleanup failed — TTL will recover after 5 minutes
      }
    }
    try {
      await (db as unknown as Querier).execute(
        sql`DELETE FROM mod_storefront_settings WHERE id = 'installed' AND value = 'pending'`,
      );
    } catch {
      // Claim release failed — TTL will recover after 5 minutes
    }
    throw e;
  }

  if (cfEnv.SESSION) {
    await setSession(cfEnv, cookies, {
      userId: createdUserId!,
      role: 'owner',
      email,
    });
  }

  return redirect('/admin');
};
