import { NotFoundError } from '../../http/errors'
import * as repo from './complaint.repo'

export async function listComplaints(
  companyId: string,
  query: { status?: string; severity?: string; category?: string; page: number; pageSize: number },
) {
  const { status, severity, category, page, pageSize } = query
  const where: Record<string, unknown> = {}
  if (status)   where.status   = status
  if (severity) where.severity = severity
  if (category) where.category = category

  const [complaints, total] = await repo.findMany(companyId, where, (page - 1) * pageSize, pageSize)
  return {
    data: complaints,
    meta: { total, page, pageSize, totalPages: Math.ceil(total / pageSize) },
  }
}

export async function getComplaint(id: string, companyId: string) {
  const complaint = await repo.findById(id, companyId)
  if (!complaint) throw new NotFoundError('Complaint not found')
  return complaint
}

export async function createComplaint(
  companyId: string,
  data: {
    reservationId?: string
    reviewId?: string
    customerId?: string
    severity: string
    category: string
    subject: string
    description?: string
    assignedTo?: string
  },
) {
  return repo.create({ companyId, ...data })
}

export async function updateComplaint(
  id: string,
  companyId: string,
  data: {
    status?: string
    severity?: string
    category?: string
    subject?: string
    description?: string
    notes?: string
    resolution?: string
    assignedTo?: string
  },
) {
  const existing = await repo.findById(id, companyId)
  if (!existing) throw new NotFoundError('Complaint not found')

  const updateData: Record<string, unknown> = { ...data }

  // When status changes to RESOLVED, set resolvedAt
  if (data.status === 'RESOLVED' && existing.status !== 'RESOLVED') {
    updateData.resolvedAt = new Date()
  }

  return repo.updateById(id, updateData)
}

export async function deleteComplaint(id: string, companyId: string) {
  const existing = await repo.findById(id, companyId)
  if (!existing) throw new NotFoundError('Complaint not found')
  await repo.deleteById(id)
  return { success: true }
}
