import "server-only";
import { cache } from "react";
import { getDb, drafts } from "@/data/db";
import { eq, and, desc } from "drizzle-orm";
import { getCurrentDid } from "@/auth";

// ============================================================================
// Types
// ============================================================================

export type DraftListItem = {
  rkey: string;
  title: string;
  description: string;
  stopsCount: number;
  accentColor: string;
  backgroundColor: string;
  updatedAt: Date;
};

export type DraftDetail = {
  rkey: string;
  version: number;
  title: string;
  description: string;
  stops: Array<{
    tid: string;
    title: string;
    content: string;
    buttonText?: string;
    external?: {
      uri: string;
      title?: string;
      description?: string;
      thumb?: string;
    };
  }>;
  accentColor: string;
  backgroundColor: string;
  createdAt: Date;
  updatedAt: Date;
};

// ============================================================================
// Auth Helper
// ============================================================================

const requireAuth = cache(async function requireAuth(): Promise<string> {
  const did = await getCurrentDid();
  if (!did) {
    throw new Error("Authentication required");
  }
  return did;
});

// ============================================================================
// Queries
// ============================================================================

export const loadDrafts = cache(async function loadDrafts(): Promise<DraftListItem[]> {
  const did = await requireAuth();
  const db = getDb();

  const rows = await db
    .select()
    .from(drafts)
    .where(eq(drafts.authorDid, did))
    .orderBy(desc(drafts.updatedAt));

  return rows.map((row) => ({
    rkey: row.rkey,
    title: row.record.title,
    description: row.record.description,
    stopsCount: row.record.stops.length,
    accentColor: row.record.accentColor,
    backgroundColor: row.record.backgroundColor,
    updatedAt: row.updatedAt,
  }));
});

export const loadDraftDetail = cache(async function loadDraftDetail(
  rkey: string,
): Promise<DraftDetail | null> {
  const did = await requireAuth();
  const db = getDb();

  const [row] = await db
    .select()
    .from(drafts)
    .where(and(eq(drafts.authorDid, did), eq(drafts.rkey, rkey)))
    .limit(1);

  if (!row) return null;

  return {
    rkey: row.rkey,
    version: row.version,
    title: row.record.title,
    description: row.record.description,
    stops: row.record.stops,
    accentColor: row.record.accentColor,
    backgroundColor: row.record.backgroundColor,
    createdAt: row.createdAt,
    updatedAt: row.updatedAt,
  };
});

export const loadDraftsBadges = cache(async function loadDraftsBadges(): Promise<
  Array<{ accentColor: string; key: string }>
> {
  const did = await requireAuth();
  const db = getDb();

  const rows = await db
    .select()
    .from(drafts)
    .where(eq(drafts.authorDid, did))
    .orderBy(desc(drafts.updatedAt))
    .limit(3);

  return rows.map((row) => ({
    key: row.rkey,
    accentColor: row.record.accentColor,
  }));
});
