export const prerender = false;

import type { APIRoute } from 'astro';
import { env } from 'cloudflare:workers';
import type { Querier } from '@platform-modules/db';
import { getSession, type SessionEnv } from '../../../lib/session.js';
import { getDb, type DbEnv } from '../../../lib/db.js';
import { setSettingValue, SETTINGS_KEYS } from '../../../lib/settings.js';
import { type AuthEnv } from '../../../lib/auth-engine.js';
import { type StorefrontLimiterEnv } from '../../../lib/rate-limit.js';

type AdminEnv = AuthEnv & SessionEnv & DbEnv & StorefrontLimiterEnv;

export const POST: APIRoute = async ({ request, cookies, redirect }) => {
  const cfEnv = env as AdminEnv | undefined;

  const session = cfEnv ? await getSession(cfEnv, cookies) : null;
  if (!session || session.role !== 'owner') {
    return redirect('/admin/login', 302);
  }

  const formData = await request.formData();
  const { db } = getDb(cfEnv!);
  const q = db as unknown as Querier;

  const fields: Array<[string, string]> = [
    [SETTINGS_KEYS.storeName, String(formData.get('storeName') ?? '')],
    [SETTINGS_KEYS.currency, String(formData.get('currency') ?? '')],
    [SETTINGS_KEYS.locale, String(formData.get('locale') ?? '')],
    [SETTINGS_KEYS.tagline, String(formData.get('tagline') ?? '')],
    [SETTINGS_KEYS.themeMode, String(formData.get('themeMode') ?? '')],
    [SETTINGS_KEYS.stripePublishableKey, String(formData.get('stripePublishableKey') ?? '')],
    [SETTINGS_KEYS.stripeTestMode, String(formData.get('stripeTestMode') ?? '')],
  ];

  for (const [key, value] of fields) {
    if (value) {
      await setSettingValue(q, key, value);
    }
  }

  return redirect('/admin/settings?saved=1', 302);
};
