import { and, eq, type SQL } from "drizzle-orm";
import { createId } from "@paralleldrive/cuid2";
import { getDb } from "../config/database.js";
import {
  notificationTemplates,
  type NotificationTemplate,
  type NewNotificationTemplate,
} from "../notifications/notifications.schema.js";

/**
 * TemplatesRepository —— 通知模板数据访问层。
 */

export async function insert(
  row: Omit<NewNotificationTemplate, "id" | "createdAt" | "updatedAt">,
): Promise<NotificationTemplate> {
  const db = getDb();
  const newTpl: NewNotificationTemplate = {
    id: createId(),
    ...row,
  };
  await db.insert(notificationTemplates).values(newTpl);
  return newTpl as NotificationTemplate;
}

export async function findById(
  id: string,
): Promise<NotificationTemplate | undefined> {
  const db = getDb();
  const [row] = await db
    .select()
    .from(notificationTemplates)
    .where(eq(notificationTemplates.id, id))
    .limit(1);
  return row;
}

export async function findByCode(
  code: string,
  locale?: string,
): Promise<NotificationTemplate | undefined> {
  const db = getDb();
  const conditions = [eq(notificationTemplates.code, code)];
  if (locale) {
    conditions.push(eq(notificationTemplates.locale, locale));
  }
  const [row] = await db
    .select()
    .from(notificationTemplates)
    .where(and(...conditions))
    .limit(1);
  return row;
}

export async function list(options: {
  type?: string;
  status?: string;
}): Promise<NotificationTemplate[]> {
  const db = getDb();
  const conditions: SQL[] = [];
  if (options.type) {
    conditions.push(
      eq(
        notificationTemplates.type,
        options.type as NotificationTemplate["type"],
      ),
    );
  }
  if (options.status) {
    conditions.push(
      eq(
        notificationTemplates.status,
        options.status as NotificationTemplate["status"],
      ),
    );
  }
  const where = conditions.length > 0 ? and(...conditions) : undefined;
  const query = db.select().from(notificationTemplates);
  return where ? query.where(where) : query;
}

export async function update(
  id: string,
  row: Partial<Omit<NewNotificationTemplate, "id" | "createdAt" | "updatedAt">>,
): Promise<void> {
  const db = getDb();
  await db
    .update(notificationTemplates)
    .set(row)
    .where(eq(notificationTemplates.id, id));
}

export async function remove(id: string): Promise<void> {
  const db = getDb();
  await db
    .delete(notificationTemplates)
    .where(eq(notificationTemplates.id, id));
}
