/**
 * Quotation Settings Service
 * Manages per-user quotation defaults, penalty config, reminder config, branding
 */

import { randomUUID } from 'crypto';
import { logger } from '@/lib/logger';
import type { UpdateQuotationSettingsInput } from '@/lib/validators/quotation-settings.validator';
import { quotationSettingsAdapter } from '@/lib/adapters/quotations';

const log = logger.scope('QuotationSettingsService');

/**
 * Get or lazily create default settings for a user
 */
export async function getOrCreateSettings(userId: string) {
  let settings = await quotationSettingsAdapter.findUnique({ where: { userId } });
  if (!settings) {
    settings = await quotationSettingsAdapter.create({
      data: { id: randomUUID(), userId, updatedAt: new Date() },
    });
    log.info('Created default quotation settings', { userId });
  }
  return settings;
}

/**
 * Update quotation settings for a user
 */
export async function updateSettings(userId: string, input: UpdateQuotationSettingsInput) {
  await getOrCreateSettings(userId);
  const updated = await quotationSettingsAdapter.update({
    where: { userId },
    data: { ...input, updatedAt: new Date() },
  });
  log.info('Updated quotation settings', { userId });
  return updated;
}
