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

vi.mock('../../lib/prisma', () => ({
  prisma: {
    $queryRawUnsafe: vi.fn(),
    customer: {
      findMany: vi.fn(),
      count: vi.fn(),
      findFirst: vi.fn(),
      create: vi.fn(),
      update: vi.fn(),
      updateMany: vi.fn(),
      findUniqueOrThrow: vi.fn(),
    },
  },
}))

import { prisma } from '../../lib/prisma'

describe('customer.repo storage-column compatibility', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    vi.resetModules()
  })

  it('includes licenseImageUrl when the deployed schema supports the column', async () => {
    vi.mocked(prisma.$queryRawUnsafe).mockResolvedValue([{ exists: true }] as never)
    const repo = await import('./customer.repo')

    await repo.findMany({ companyId: 'company_1' }, 0, 20)

    expect(prisma.customer.findMany).toHaveBeenCalledWith(expect.objectContaining({
      select: expect.objectContaining({ licenseImageUrl: true }),
    }))
    expect(prisma.customer.count).toHaveBeenCalledWith({ where: { companyId: 'company_1' } })
  })

  it('strips licenseImageUrl from writes when the old deployed schema lacks the column', async () => {
    vi.mocked(prisma.$queryRawUnsafe).mockResolvedValue([{ exists: false }] as never)
    const repo = await import('./customer.repo')

    await repo.create({ companyId: 'company_1', email: 'renter@example.test', licenseImageUrl: '/storage/private.png' })

    expect(prisma.customer.create).toHaveBeenCalledWith({
      data: { companyId: 'company_1', email: 'renter@example.test' },
      select: expect.not.objectContaining({ licenseImageUrl: true }),
    })
  })

  it('scopes customer updates by id and company id without querying schema support', async () => {
    const repo = await import('./customer.repo')

    await repo.updateMany('customer_1', 'company_1', { flagged: true })

    expect(prisma.customer.updateMany).toHaveBeenCalledWith({
      where: { id: 'customer_1', companyId: 'company_1' },
      data: { flagged: true },
    })
    expect(prisma.$queryRawUnsafe).not.toHaveBeenCalled()
  })
})
