import { adapters, migrationFields, newUuid } from '@/services/serviceConfig';
import { auditService } from '@/services/auditService';
export const manufacturingService = {
  list: () => adapters.database.list('ManufacturingJob'),
  forOrder: (order_uuid) => adapters.database.filter('ManufacturingJob', { order_uuid }),
  forProject: (project_uuid) => adapters.database.filter('ManufacturingJob', { project_uuid }),
  forCustomer: (customer_uuid) => adapters.database.filter('ManufacturingJob', { customer_uuid }),
  get: async (uuid) => (await adapters.database.filter('ManufacturingJob', { uuid }, '-updated_date', 1))[0],
  async create(data, actor) { const record = await adapters.database.create('ManufacturingJob', { ...data, uuid: newUuid('mfg'), job_reference: `MFG-${Date.now().toString().slice(-6)}`, status: data.status || 'Waiting', data_origin: data.data_origin || 'Workshop Created', ...migrationFields(actor) }); await auditService.record('manufacturing_created', 'ManufacturingJob', record.uuid, `Created job ${record.job_reference}`, actor); return record; },
  async setStatus(id, uuid, status, actor) { const patch = { status, updated_by_name: actor }; if (status === 'Complete') patch.completed_date = new Date().toISOString().slice(0, 10); if (status === 'Printing' && !actor._noStart) patch.started_date = new Date().toISOString().slice(0, 10); await adapters.database.update('ManufacturingJob', id, patch); return auditService.record('manufacturing_status', 'ManufacturingJob', uuid, `Status → ${status}`, actor); },
  async linkCover(id, uuid, coverUuid, actor) { await adapters.database.update('ManufacturingJob', id, { completed_cover_uuid: coverUuid, updated_by_name: actor }); return auditService.record('manufacturing_cover_linked', 'ManufacturingJob', uuid, 'Linked to completed cover', actor); },
  archive: async (record, actor) => { await adapters.database.archive('ManufacturingJob', record.id); return auditService.record('manufacturing_archived', 'ManufacturingJob', record.uuid, 'Job archived', actor); },
  restore: async (record, actor) => { await adapters.database.restore('ManufacturingJob', record.id); return auditService.record('manufacturing_restored', 'ManufacturingJob', record.uuid, 'Job restored', actor); },
};