/**
 * Repository für `section_templates` — wiederverwendbare MJML-Bausteine pro Workspace.
 *
 * Trennung zu `template-repo.ts`:
 *   `templates`-Tabelle = ganze Mail (briefing+tiptap snapshot).
 *   `section_templates`-Tabelle = einzelner MJML-Block der ins Briefing eingebunden werden kann.
 *
 * `isSystem=true`-Rows kommen aus dem Seed-Script und sind nicht löschbar.
 * Custom-Rows (User-eigene Sections) können editiert/gelöscht werden.
 */

import { eq, and, desc } from 'drizzle-orm';
import { db } from './client';
import {
  sectionTemplates,
  workspaces,
  type SectionTemplate,
  type SectionTemplateInsert,
} from './schema';

export type SectionKind = 'contact_service' | 'app_download' | 'testimonial' | 'faq' | 'custom';
export type SectionPosition = 'before_cta' | 'after_cta' | 'before_signature' | 'after_signature';
export type SectionBodyMode = 'tiptap' | 'mjml_raw' | 'html_raw';

export interface SectionTemplateSummary {
  id: string;
  workspaceId: string;
  kind: SectionKind;
  name: string;
  description: string | null;
  defaultContentJson: unknown;
  mjmlBlock: string;
  aiPromptHint: string | null;
  defaultPosition: SectionPosition;
  bodyMode: SectionBodyMode;
  isSystem: boolean;
  createdAt: Date;
  updatedAt: Date;
}

function toSummary(t: SectionTemplate): SectionTemplateSummary {
  return {
    id: t.id,
    workspaceId: t.workspaceId,
    kind: t.kind as SectionKind,
    name: t.name,
    description: t.description,
    defaultContentJson: t.defaultContentJson,
    mjmlBlock: t.mjmlBlock,
    aiPromptHint: t.aiPromptHint,
    defaultPosition: t.defaultPosition as SectionPosition,
    bodyMode: (t.bodyMode ?? 'tiptap') as SectionBodyMode,
    isSystem: t.isSystem,
    createdAt: t.createdAt,
    updatedAt: t.updatedAt,
  };
}

export function listSectionTemplatesByBrand(workspaceId: string, kindFilter?: SectionKind): SectionTemplateSummary[] {
  const whereClause = kindFilter
    ? and(eq(sectionTemplates.workspaceId, workspaceId), eq(sectionTemplates.kind, kindFilter))
    : eq(sectionTemplates.workspaceId, workspaceId);
  const rows = db
    .select()
    .from(sectionTemplates)
    .where(whereClause)
    .orderBy(desc(sectionTemplates.isSystem), sectionTemplates.kind, sectionTemplates.name)
    .all();
  return rows.map(toSummary);
}

export function listSectionTemplatesByBrandSlug(slug: string, kindFilter?: SectionKind): SectionTemplateSummary[] {
  const workspace = db.select().from(workspaces).where(eq(workspaces.slug, slug)).get();
  if (!workspace) return [];
  return listSectionTemplatesByBrand(workspace.id, kindFilter);
}

export function getSectionTemplate(id: string): SectionTemplateSummary | undefined {
  const row = db.select().from(sectionTemplates).where(eq(sectionTemplates.id, id)).get();
  return row ? toSummary(row) : undefined;
}

export function createSectionTemplate(input: SectionTemplateInsert): SectionTemplateSummary {
  const id = input.id ?? crypto.randomUUID();
  db.insert(sectionTemplates).values({ ...input, id }).run();
  const row = db.select().from(sectionTemplates).where(eq(sectionTemplates.id, id)).get()!;
  return toSummary(row);
}

export function upsertSystemSectionTemplate(
  workspaceId: string,
  kind: SectionKind,
  values: Omit<SectionTemplateInsert, 'id' | 'workspaceId' | 'kind' | 'isSystem'>,
): SectionTemplateSummary {
  // System-Templates sind eindeutig per (workspaceId, kind) — Seed läuft idempotent.
  const existing = db
    .select()
    .from(sectionTemplates)
    .where(
      and(
        eq(sectionTemplates.workspaceId, workspaceId),
        eq(sectionTemplates.kind, kind),
        eq(sectionTemplates.isSystem, true),
      ),
    )
    .get();

  if (existing) {
    db.update(sectionTemplates)
      .set({ ...values, updatedAt: new Date() })
      .where(eq(sectionTemplates.id, existing.id))
      .run();
    const row = db.select().from(sectionTemplates).where(eq(sectionTemplates.id, existing.id)).get()!;
    return toSummary(row);
  }

  return createSectionTemplate({
    workspaceId,
    kind,
    isSystem: true,
    ...values,
  });
}

export function updateSectionTemplate(
  id: string,
  patch: Partial<Omit<SectionTemplateInsert, 'id' | 'workspaceId' | 'isSystem'>>,
): SectionTemplateSummary | undefined {
  const existing = getSectionTemplate(id);
  if (!existing) return undefined;
  db.update(sectionTemplates)
    .set({ ...patch, updatedAt: new Date() })
    .where(eq(sectionTemplates.id, id))
    .run();
  return getSectionTemplate(id);
}

/**
 * Custom-Sections sind löschbar, System-Sections nicht — analog zur Logik in `template-repo`.
 * Caller bekommt false zurück wenn die Section System oder unbekannt ist.
 */
export function deleteSectionTemplate(id: string): boolean {
  const existing = db.select().from(sectionTemplates).where(eq(sectionTemplates.id, id)).get();
  if (!existing || existing.isSystem) return false;
  const r = db.delete(sectionTemplates).where(eq(sectionTemplates.id, id)).run();
  return r.changes > 0;
}
