import { findAll, findById, insert, update, softDelete, findByName } from '../repositories/metalType.repo.js';
import { hasProductsReferencing } from '../repositories/product.repo.js';
import { createWithId } from '../utils/id.js';
import { NotFoundError, ConflictError } from '../utils/errors.js';
import { emitter } from '../events/emitter.js';
import type { MetalType } from '../types/index.js';

export async function list(): Promise<MetalType[]> {
  return findAll();
}

export async function get(id: string): Promise<MetalType> {
  const item = await findById(id);
  if (!item) throw new NotFoundError('MetalType not found');
  return item;
}

export async function create(name: string, userId: string): Promise<MetalType> {
  const duplicate = await findByName(name);
  if (duplicate) throw new ConflictError(`"${name}" already exists`);

  const { id } = await createWithId('metal_types', 'MT', (id) => insert(name, id, userId));
  const item = await findById(id);
  if (!item) throw new NotFoundError('MetalType not found');
  emitter.emit('activity.create', { entity_type: 'metal_types', entity_id: id, action: 'created', user_id: userId });
  return item;
}

export async function updateItem(id: string, name: string, userId: string): Promise<MetalType> {
  const existing = await findById(id);
  if (!existing) throw new NotFoundError('MetalType not found');
  const duplicate = await findByName(name, id);
  if (duplicate) throw new ConflictError(`"${name}" already exists`);
  await update(id, name, userId);
  emitter.emit('activity.create', { entity_type: 'metal_types', entity_id: id, action: 'updated', user_id: userId });
  return get(id);
}

export async function remove(id: string, userId: string): Promise<void> {
  const existing = await findById(id);
  if (!existing) throw new NotFoundError('MetalType not found');
  if (await hasProductsReferencing('metal_type_id', id)) {
    throw new ConflictError('This metal type is used by existing products and cannot be deleted');
  }
  await softDelete(id, userId);
  emitter.emit('activity.create', { entity_type: 'metal_types', entity_id: id, action: 'deleted', user_id: userId });
}
