import fs from 'fs'
import os from 'os'
import path from 'path'
import { describe, expect, it, vi } from 'vitest'

const storageRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'rdg-e2e-storage-'))
process.env.FILE_STORAGE_ROOT = storageRoot
process.env.NODE_ENV = 'test'

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 { createApp } from '../../app'

const app = createApp()

describe('storage boundary e2e smoke', () => {
  it('serves public storage assets cross-origin but hides customer identity document paths', async () => {
    const publicDir = path.join(storageRoot, 'public', 'companies', 'company_1', 'vehicles')
    fs.mkdirSync(publicDir, { recursive: true })
    fs.writeFileSync(path.join(publicDir, 'vehicle_1.jpg'), 'image-bytes')

    const asset = await request(app).get('/storage/companies/company_1/vehicles/vehicle_1.jpg')
    expect(asset.status).toBe(200)
    expect(asset.headers['cross-origin-resource-policy']).toBe('cross-origin')
    expect(asset.body.toString()).toBe('image-bytes')

    const protectedDoc = await request(app).get('/storage/companies/company_1/customers/customer_1/license.jpg')
    expect(protectedDoc.status).toBe(404)
  })
})
