import { PlatformError } from '../../kernel/errors.mjs';
import {
  evaluateThemeAccessibility, getBaseThemeValues, getBuiltinThemes, getThemeContract,
  resolveThemeValues, validateThemeDefinition, validateThemePreference,
} from '../../core/themes/theme-contract.mjs';
import {
  deleteThemeProfile, ensureThemeSchema, getThemeProfile, getThemeSystemDefault,
  getUserThemePreference, listThemeProfiles, saveThemeProfile, saveThemeSystemDefault,
  saveUserThemePreference,
} from './repository.mjs';

function decorate(profile) {
  return {
    ...profile,
    builtin: false,
    resolved_values: resolveThemeValues({ baseTheme: profile.base_theme, values: profile.values }),
    accessibility: evaluateThemeAccessibility({ baseTheme: profile.base_theme, values: profile.values }),
  };
}

function customExists(id) {
  return Boolean(getThemeProfile(id));
}

function effectivePreference(userPreference, systemDefault) {
  return userPreference.theme_id === 'inherit' ? { ...systemDefault, inherited: true } : { ...userPreference, inherited: false };
}

export function createThemeService() {
  ensureThemeSchema();
  return Object.freeze({
    health() {
      ensureThemeSchema();
      return { ok: true, profiles: listThemeProfiles().length, contract: getThemeContract().contractVersion };
    },
    catalog(userId) {
      const custom = listThemeProfiles().map(decorate);
      const preference = getUserThemePreference(userId);
      const systemDefault = getThemeSystemDefault();
      return {
        contract: getThemeContract(),
        builtin: getBuiltinThemes(),
        custom,
        preference,
        system_default: systemDefault,
        effective_preference: effectivePreference(preference, systemDefault),
      };
    },
    validate(input) {
      const theme = validateThemeDefinition(input, { allowExistingId: true });
      return { theme, resolved_values: resolveThemeValues({ baseTheme: theme.base_theme, values: theme.values }), accessibility: theme.accessibility };
    },
    create(input, userId) {
      const theme = validateThemeDefinition(input);
      if (getThemeProfile(theme.id)) throw new PlatformError('Theme-ID ist bereits vorhanden.', { code: 'THEME_DUPLICATE', status: 409, expose: true });
      return decorate(saveThemeProfile(theme, userId));
    },
    update(id, input, userId) {
      if (!getThemeProfile(id)) throw new PlatformError('Theme wurde nicht gefunden.', { code: 'THEME_NOT_FOUND', status: 404, expose: true });
      const theme = validateThemeDefinition({ ...input, id }, { allowExistingId: true });
      return decorate(saveThemeProfile(theme, userId));
    },
    remove(id) {
      if (!getThemeProfile(id)) throw new PlatformError('Theme wurde nicht gefunden.', { code: 'THEME_NOT_FOUND', status: 404, expose: true });
      deleteThemeProfile(id);
      return { ok: true, id };
    },
    saveUserPreference(userId, input) {
      const preference = validateThemePreference(input, { customThemeExists: customExists });
      return saveUserThemePreference(userId, preference);
    },
    saveSystemDefault(input) {
      const preference = validateThemePreference(input, { customThemeExists: customExists });
      if (preference.theme_id === 'inherit') throw new PlatformError('Der Systemstandard kann nicht auf „Vererben“ gesetzt werden.', { code: 'THEME_SYSTEM_INHERIT_INVALID', status: 400, expose: true });
      return saveThemeSystemDefault(preference);
    },
    exportTheme(id) {
      const profile = getThemeProfile(id);
      if (!profile) throw new PlatformError('Theme wurde nicht gefunden.', { code: 'THEME_NOT_FOUND', status: 404, expose: true });
      return { schemaVersion: 1, type: 'vendoo-theme', theme: { id: profile.id, name: profile.name, base_theme: profile.base_theme, values: profile.values } };
    },
  });
}

export { getBaseThemeValues };
