import request from 'supertest'
import { prisma } from '../../lib/prisma'
import { createApp } from '../../app'
import { authHeader, createCompanyWithEmployee, signEmployeeToken } from '../helpers/fixtures'

const app = createApp()

describe('Subscription entitlements integration', () => {
  it('returns the company entitlement derived from the persisted subscription status', async () => {
    const { company, employee } = await createCompanyWithEmployee({ role: 'OWNER' })
    const token = signEmployeeToken(employee.id, company.id, 'OWNER')

    await prisma.subscription.update({
      where: { companyId: company.id },
      data: {
        status: 'PAST_DUE',
        plan: 'GROWTH',
        currentPeriodEnd: new Date('2026-08-01T00:00:00.000Z'),
      },
    })

    const res = await request(app)
      .get('/api/v1/subscriptions/entitlement')
      .set(authHeader(token))

    expect(res.status).toBe(200)
    expect(res.body.data).toEqual(expect.objectContaining({
      companyId: company.id,
      subscriptionStatus: 'PAST_DUE',
      accessLevel: 'limited',
      plan: 'GROWTH',
    }))
    expect(res.body.data.currentPeriodEnd).toBeTruthy()
  })

  it('denies authenticated subscription routes when no bearer token is supplied', async () => {
    const res = await request(app).get('/api/v1/subscriptions/entitlement')

    expect(res.status).toBe(401)
  })
})
