import { eq, desc } from 'drizzle-orm';
import { db } from './client';
import { templates, campaigns, workspaces, type Template } from './schema';
import { createDraft, type DraftSummary } from './draft-repo';

/**
 * Templates sind wiederverwendbare Briefing+Editor-Snapshots, die NICHT an eine
 * konkrete Campaign hängen. User können einen Draft "als Vorlage speichern" und
 * später daraus einen neuen Draft instanziieren.
 */

export interface TemplateSummary {
  id: string;
  name: string;
  description: string | null;
  workspaceId: string;
  workspaceSlug: string;
  brandName: string;
  brandPrimaryColor: string;
  createdAt: Date;
  updatedAt: Date;
}

function joinTemplate(t: Template, b: { id: string; slug: string; name: string; primaryColor: string }): TemplateSummary {
  return {
    id: t.id,
    name: t.name,
    description: t.description,
    workspaceId: t.workspaceId,
    workspaceSlug: b.slug,
    brandName: b.name,
    brandPrimaryColor: b.primaryColor,
    createdAt: t.createdAt,
    updatedAt: t.updatedAt,
  };
}

export function listTemplates(): TemplateSummary[] {
  const rows = db.select({ t: templates, b: workspaces })
    .from(templates)
    .innerJoin(workspaces, eq(templates.workspaceId, workspaces.id))
    .orderBy(desc(templates.updatedAt))
    .all();
  return rows.map((r) => joinTemplate(r.t, r.b));
}

export function getTemplate(id: string): Template | undefined {
  return db.select().from(templates).where(eq(templates.id, id)).get();
}

/**
 * Speichert einen Draft als Vorlage. Kopiert Briefing + Tiptap-State, NICHT
 * generierte Outputs (Strategy, HTML, Spam) — diese sind draft-spezifisch.
 */
export function saveAsTemplate(input: {
  draftId: string;
  name: string;
  description?: string;
}): TemplateSummary {
  const draft = db.select().from(campaigns).where(eq(campaigns.id, input.draftId)).get();
  if (!draft) throw new Error(`Draft not found: ${input.draftId}`);
  const workspace = db.select().from(workspaces).where(eq(workspaces.id, draft.workspaceId)).get();
  if (!workspace) throw new Error(`Workspace not found: ${draft.workspaceId}`);

  const id = crypto.randomUUID();
  db.insert(templates).values({
    id,
    workspaceId: draft.workspaceId,
    name: input.name,
    description: input.description,
    tiptapJson: draft.tiptapJson,
    briefingJson: draft.briefingJson,
  }).run();

  const t = db.select().from(templates).where(eq(templates.id, id)).get()!;
  return joinTemplate(t, workspace);
}

/**
 * Erzeugt einen neuen Draft aus einer Vorlage. Kopiert Briefing + Tiptap-State
 * in einen frischen Campaign-Row mit status='draft'. Die Vorlage selbst bleibt
 * unverändert.
 */
export function createDraftFromTemplate(templateId: string, overrideName?: string): DraftSummary {
  const t = getTemplate(templateId);
  if (!t) throw new Error(`Template not found: ${templateId}`);

  return createDraft({
    workspaceId: t.workspaceId,
    name: overrideName ?? `${t.name} (Entwurf)`,
    briefingJson: (t.briefingJson as object) ?? {},
    tiptapJson: (t.tiptapJson as object) ?? {},
  });
}

export function deleteTemplate(id: string): boolean {
  const r = db.delete(templates).where(eq(templates.id, id)).run();
  return r.changes > 0;
}
