/**
 * Theme repository — cloud-agnostic via @bytelyst/datastore.
 */

import { getCollection } from '../../lib/datastore.js';
import type { ThemeDoc } from './types.js';

function collection() {
  return getCollection<ThemeDoc>('themes', '/id');
}

export async function getAll(productId: string): Promise<ThemeDoc[]> {
  return collection().findMany({
    filter: { productId, type: 'theme' },
    sort: { created_at: -1 },
  });
}

export async function getById(id: string): Promise<ThemeDoc | null> {
  try {
    return await collection().findById(id, id);
  } catch {
    return null;
  }
}

export async function getActive(productId: string): Promise<ThemeDoc | null> {
  return collection().findOne({
    filter: { productId, type: 'theme', is_active: true },
    sort: { is_default: -1, created_at: -1 },
    limit: 1,
  });
}

export async function create(theme: ThemeDoc): Promise<ThemeDoc> {
  return collection().create(theme);
}

export async function update(
  id: string,
  updates: Record<string, unknown>
): Promise<ThemeDoc | null> {
  try {
    return await collection().update(id, id, {
      ...updates,
      updated_at: new Date().toISOString(),
    } as Partial<ThemeDoc>);
  } catch {
    return null;
  }
}

export async function setActive(id: string, productId: string): Promise<boolean> {
  const theme = await getById(id);
  if (!theme) return false;

  // Deactivate all others for this product
  const activeThemes = await collection().findMany({
    filter: { productId, type: 'theme', is_active: true, id: { $ne: id } },
  });

  for (const item of activeThemes) {
    await collection().update(item.id, item.id, {
      is_active: false,
      updated_at: new Date().toISOString(),
    } as Partial<ThemeDoc>);
  }

  // Activate the target theme
  await update(id, { is_active: true });
  return true;
}

export async function remove(id: string): Promise<boolean> {
  try {
    await collection().delete(id, id);
    return true;
  } catch {
    return false;
  }
}
