import { isLocale, type Locale } from "@/i18n/routes";
import { getDict } from "@/i18n/dictionaries";
import { getDb } from "@/lib/db";
import { getProfile } from "@/lib/models";
import { AdminShell } from "@/components/admin/admin-shell";
import { ProfileForm } from "@/components/admin/profile-form";
import { seedIfEmpty } from "@/lib/seed";
import type Database from "better-sqlite3";

type FullProfileRow = {
  bio_de: string;
  bio_en: string;
  facts_de: string;
  facts_en: string;
};

function readFullProfile(db: Database.Database) {
  const row = db.prepare("SELECT bio_de, bio_en, facts_de, facts_en FROM profile WHERE id = 1").get() as FullProfileRow | undefined;
  if (!row) throw new Error("Profile-Row fehlt nach Seed");
  return {
    bioDe: row.bio_de,
    bioEn: row.bio_en,
    factsDe: JSON.parse(row.facts_de) as string[],
    factsEn: JSON.parse(row.facts_en) as string[],
  };
}

export default async function ProfileAdminPage() {
  const locale: Locale = "de";
  const dict = getDict(locale);
  const db = getDb();
  seedIfEmpty(db);
  const profile = getProfile(db, locale);
  const full = readFullProfile(db);
  return (
    <AdminShell locale={locale} title={dict.admin.profileTitle} active="profile">
      <ProfileForm
        locale={locale}
        initial={{
          handle: profile.handle,
          realName: profile.realName,
          role: profile.role,
          location: profile.location,
          bioDe: full.bioDe,
          bioEn: full.bioEn,
          factsDe: full.factsDe,
          factsEn: full.factsEn,
          links: profile.links,
          bio: profile.bio,
          facts: profile.facts,
          updatedAt: profile.updatedAt,
        }}
      />
    </AdminShell>
  );
}
