import { vi } from 'vitest'

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

vi.mock('../../lib/redis', () => ({
  redis: {
    on: vi.fn(),
    get: vi.fn(),
    set: vi.fn(),
    del: vi.fn(),
    quit: vi.fn(),
  },
}))

import request from 'supertest'
import { describe, expect, it } from 'vitest'
import { createApp } from '../../app'

const app = createApp()

describe('API foundation integration', () => {
  it('GET /health returns a stable health contract', async () => {
    const res = await request(app).get('/health')

    expect(res.status).toBe(200)
    expect(res.body).toEqual({
      status: 'ok',
      version: '1.0.0',
      timestamp: expect.any(String),
    })
    expect(new Date(res.body.timestamp).toString()).not.toBe('Invalid Date')
  })

  it('GET /api/v1 returns the public API index', async () => {
    const res = await request(app).get('/api/v1')

    expect(res.status).toBe(200)
    expect(res.body).toEqual({
      name: 'rentaldrivego-api',
      version: '1.0.0',
      baseUrl: '/api/v1',
      health: '/health',
      docs: '/api/v1/docs',
      openApi: '/api/v1/openapi.json',
    })
  })

  it('GET /api/v1/docs exposes documented routes and documentation links', async () => {
    const res = await request(app).get('/api/v1/docs')

    expect(res.status).toBe(200)
    expect(res.body).toEqual(expect.objectContaining({
      name: 'rentaldrivego-api',
      version: '1.0.0',
      baseUrl: '/api/v1',
      swaggerUi: '/docs',
      openApi: '/api/v1/openapi.json',
      routes: expect.any(Array),
    }))
    expect(res.body.routes).toEqual(expect.arrayContaining([
      expect.objectContaining({ method: 'GET', path: '/health' }),
      expect.objectContaining({ method: 'GET', path: '/api/v1/vehicles' }),
      expect.objectContaining({ method: 'POST', path: '/api/v1/admin/auth/login' }),
    ]))
  })

  it('GET /api/v1/openapi.json returns the OpenAPI document', async () => {
    const res = await request(app).get('/api/v1/openapi.json')

    expect(res.status).toBe(200)
    expect(res.body.openapi).toMatch(/^3\./)
    expect(res.body.info).toEqual(expect.objectContaining({ title: expect.any(String), version: expect.any(String) }))
    expect(res.body.paths).toHaveProperty('/health')
  })

  it('blocks legacy anonymous access to customer identity document storage paths', async () => {
    const res = await request(app).get('/storage/companies/company_1/customers/customer_1/passport.jpg')

    expect(res.status).toBe(404)
    expect(res.text).toBe('')
  })

  it('allows public storage misses to be returned cross-origin instead of browser-blocked', async () => {
    const res = await request(app).get('/storage/vehicles/missing-photo.jpg')

    expect(res.status).toBe(404)
    expect(res.headers['cross-origin-resource-policy']).toBe('cross-origin')
  })
})
