import type { FreshnessRulesRepository } from './freshness-rules.repository.js';
import { FreshnessRuleSource } from '@meshitrack/shared';
import type {
  CreateFreshnessRuleInput,
  UpdateFreshnessRuleInput,
  FreshnessRuleQueryInput,
} from '@meshitrack/shared';
import { NotFoundError, BadRequestError } from '../../common/errors.js';

interface Deps {
  freshnessRulesRepository: FreshnessRulesRepository;
}

export class FreshnessRulesService {
  private readonly freshnessRulesRepository: FreshnessRulesRepository;

  public constructor({ freshnessRulesRepository }: Deps) {
    this.freshnessRulesRepository = freshnessRulesRepository;
  }

  public async list(householdId: string, query: FreshnessRuleQueryInput) {
    return this.freshnessRulesRepository.findByHousehold(householdId, query);
  }

  public async create(data: CreateFreshnessRuleInput, householdId: string) {
    return this.freshnessRulesRepository.create({
      ...data,
      householdId,
      source: FreshnessRuleSource.HOUSEHOLD,
    });
  }

  public async update(id: string, householdId: string, data: UpdateFreshnessRuleInput) {
    const existing = await this.freshnessRulesRepository.findById(id);
    if (!existing) throw new NotFoundError('Freshness rule not found');

    const rec = existing as Record<string, unknown>;
    if (rec.source === FreshnessRuleSource.SYSTEM && rec.householdId == null) {
      throw new BadRequestError('Cannot modify system rules. Create a household override instead.');
    }
    if (rec.householdId && rec.householdId !== householdId) {
      throw new NotFoundError('Freshness rule not found');
    }

    const updated = await this.freshnessRulesRepository.update(id, householdId, data);
    if (!updated) throw new NotFoundError('Freshness rule not found');
    return updated;
  }

  public async delete(id: string, householdId: string) {
    const existing = await this.freshnessRulesRepository.findById(id);
    if (!existing) throw new NotFoundError('Freshness rule not found');

    const rec = existing as Record<string, unknown>;
    if (rec.source === FreshnessRuleSource.SYSTEM && rec.householdId == null) {
      throw new BadRequestError('Cannot delete system rules');
    }
    if (rec.householdId && rec.householdId !== householdId) {
      throw new NotFoundError('Freshness rule not found');
    }

    await this.freshnessRulesRepository.delete(id, householdId);
  }
}
