import { beforeEach, describe, expect, it, vi } from 'vitest'

vi.mock('../../lib/prisma', () => ({
  prisma: {
    complaint: { findMany: vi.fn(), count: vi.fn(), findFirst: vi.fn(), create: vi.fn(), update: vi.fn(), delete: vi.fn() },
  },
}))

import { prisma } from '../../lib/prisma'
import * as repo from './complaint.repo'

describe('complaint.repo edge behavior', () => {
  beforeEach(() => vi.clearAllMocks())

  it('lists complaints with company-scoped filters and deterministic ordering', async () => {
    vi.mocked(prisma.complaint.findMany).mockResolvedValue([] as never)
    vi.mocked(prisma.complaint.count).mockResolvedValue(0 as never)

    await repo.findMany('company_1', { status: 'OPEN', severity: 'LEVEL_2' }, 40, 20)

    const where = { companyId: 'company_1', status: 'OPEN', severity: 'LEVEL_2' }
    expect(prisma.complaint.findMany).toHaveBeenCalledWith(expect.objectContaining({
      where,
      skip: 40,
      take: 20,
      orderBy: { createdAt: 'desc' },
    }))
    expect(prisma.complaint.count).toHaveBeenCalledWith({ where })
  })

  it('creates complaints with linked reservation, review and customer ids preserved', async () => {
    await repo.create({
      companyId: 'company_1',
      reservationId: 'reservation_1',
      reviewId: 'review_1',
      customerId: 'customer_1',
      severity: 'LEVEL_3',
      category: 'DAMAGE_CLAIM',
      subject: 'Damage dispute',
      assignedTo: 'employee_1',
    })

    expect(prisma.complaint.create).toHaveBeenCalledWith(expect.objectContaining({
      data: {
        companyId: 'company_1',
        reservationId: 'reservation_1',
        reviewId: 'review_1',
        customerId: 'customer_1',
        severity: 'LEVEL_3',
        category: 'DAMAGE_CLAIM',
        subject: 'Damage dispute',
        assignedTo: 'employee_1',
      },
    }))
  })

  it('updates by complaint id without accepting a company id bypass from caller data', async () => {
    await repo.updateById('complaint_1', { status: 'RESOLVED', resolution: 'Refunded deposit' })

    expect(prisma.complaint.update).toHaveBeenCalledWith(expect.objectContaining({
      where: { id: 'complaint_1' },
      data: { status: 'RESOLVED', resolution: 'Refunded deposit' },
    }))
  })

  it('deletes by primary id', async () => {
    await repo.deleteById('complaint_1')

    expect(prisma.complaint.delete).toHaveBeenCalledWith({ where: { id: 'complaint_1' } })
  })
})
