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

vi.mock('../../lib/prisma', () => ({
  prisma: {
    subscription: {
      findUnique: vi.fn(),
    },
  },
}))

import { prisma } from '../../lib/prisma'
import { resolveSettingsEntitlements, resolveSettingsMenu } from './settingsEntitlements'

describe('settingsEntitlements', () => {
  beforeEach(() => {
    vi.clearAllMocks()
  })

  it('keeps company profile available while locking premium STARTER capabilities', async () => {
    vi.mocked(prisma.subscription.findUnique).mockResolvedValue({
      plan: 'STARTER',
      status: 'ACTIVE',
      currentPeriodEnd: null,
      trialEndAt: null,
    } as never)

    const result = await resolveSettingsEntitlements('company_1')

    expect(result.features['settings.company_profile']).toMatchObject({ available: true, editable: true })
    expect(result.features['settings.renter_payments']).toMatchObject({
      available: false,
      editable: false,
      requiredPlan: 'GROWTH',
    })
    expect(result.features['settings.accounting_scheduled_delivery']).toMatchObject({
      available: false,
      requiredPlan: 'PRO',
    })
  })

  it('returns the approved seven settings sections with localized locked states', async () => {
    vi.mocked(prisma.subscription.findUnique).mockResolvedValue({
      plan: 'STARTER',
      status: 'ACTIVE',
      currentPeriodEnd: null,
      trialEndAt: null,
    } as never)

    const result = await resolveSettingsMenu('company_1', 'fr')

    expect(result.items).toHaveLength(7)
    expect(result.items.map((item) => item.sectionKey)).toEqual([
      'company',
      'carplace',
      'payments',
      'rental-policies',
      'insurance',
      'pricing',
      'accounting',
    ])
    expect(result.items.find((item) => item.sectionKey === 'payments')).toMatchObject({
      label: 'Méthodes de paiement',
      state: 'LOCKED',
      requiredPlan: 'GROWTH',
    })
  })

  it('makes premium features read-only during past-due access', async () => {
    vi.mocked(prisma.subscription.findUnique).mockResolvedValue({
      plan: 'PRO',
      status: 'PAST_DUE',
      currentPeriodEnd: null,
      trialEndAt: null,
    } as never)

    const result = await resolveSettingsEntitlements('company_1')

    expect(result.features['settings.company_profile']).toMatchObject({ available: true, editable: true })
    expect(result.features['settings.pricing_rules']).toMatchObject({ available: true, editable: false })
  })
})
