import { beforeEach, describe, expect, it, vi } from 'vitest'
import type { NextFunction, Request, Response } from 'express'

import { requireSubscription } from './requireSubscription'

function responseStub() {
  const res = { status: vi.fn(), json: vi.fn() }
  res.status.mockReturnValue(res)
  res.json.mockReturnValue(res)
  return res as unknown as Response & typeof res
}

describe('requireSubscription middleware', () => {
  beforeEach(() => {
    process.env.NEXT_PUBLIC_DASHBOARD_URL = 'https://dashboard.example.test'
  })

  it('requires tenant/company context first', () => {
    const req = {} as Request
    const res = responseStub()
    const next = vi.fn() as NextFunction

    requireSubscription(req, res, next)

    expect(res.status).toHaveBeenCalledWith(401)
    expect(res.json).toHaveBeenCalledWith({ error: 'unauthenticated', message: 'No company context', statusCode: 401 })
    expect(next).not.toHaveBeenCalled()
  })

  it('blocks suspended companies with a subscription recovery URL', () => {
    const req = { company: { status: 'SUSPENDED' } } as Request
    const res = responseStub()
    const next = vi.fn() as NextFunction

    requireSubscription(req, res, next)

    expect(res.status).toHaveBeenCalledWith(402)
    expect(res.json).toHaveBeenCalledWith({
      error: 'subscription_suspended',
      message: 'Your account has been suspended. Please contact support or renew your subscription.',
      statusCode: 402,
      billingUrl: 'https://dashboard.example.test/subscription',
    })
    expect(next).not.toHaveBeenCalled()
  })

  it('blocks pending companies with setup guidance', () => {
    const req = { company: { status: 'PENDING' } } as Request
    const res = responseStub()
    const next = vi.fn() as NextFunction

    requireSubscription(req, res, next)

    expect(res.status).toHaveBeenCalledWith(402)
    expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
      error: 'subscription_pending',
      message: 'Your account is pending activation. Please complete your subscription setup.',
    }))
    expect(next).not.toHaveBeenCalled()
  })

  it('allows active companies through', () => {
    const req = { company: { status: 'ACTIVE' } } as Request
    const res = responseStub()
    const next = vi.fn() as NextFunction

    requireSubscription(req, res, next)

    expect(next).toHaveBeenCalledTimes(1)
    expect(res.status).not.toHaveBeenCalled()
  })
})
