import { describe, expect, it } from 'vitest';
import request from 'supertest';
import express from 'express';
import { z } from 'zod';
import { createApp } from '../src/app';
import { validate } from '../src/middleware/validate';
import { errorHandler } from '../src/middleware/errors';
import { paginationQuery, sortQuery } from '../src/lib/pagination';

const up = () => createApp({ ping: async () => true });
const down = () => createApp({ ping: async () => false });

describe('GET /api/v1/health', () => {
  it('returns 200 when the database answers', async () => {
    const res = await request(up()).get('/api/v1/health');
    expect(res.status).toBe(200);
    expect(res.body).toMatchObject({ ok: true, db: 'up' });
    expect(res.headers['cache-control']).toBe('no-store');
  });
  it('returns 503 when the database is down', async () => {
    const res = await request(down()).get('/api/v1/health');
    expect(res.status).toBe(503);
    expect(res.body).toMatchObject({ ok: false, db: 'down' });
  });
});

describe('error shape', () => {
  it('unknown public route → 404 { error: { code, message } }', async () => {
    const res = await request(up()).get('/api/v1/nope');
    expect(res.status).toBe(404);
    expect(res.body.error.code).toBe('not_found');
    expect(typeof res.body.error.message).toBe('string');
  });
  it('admin routes need a login (even unknown ones, so routes are not revealed) and are never cached', async () => {
    const res = await request(up()).get('/api/v1/admin/nope');
    expect(res.status).toBe(401);
    expect(res.headers['cache-control']).toBe('no-store');
  });
  it('malformed JSON → 400 invalid_json', async () => {
    const res = await request(up())
      .post('/api/v1/anything')
      .set('Content-Type', 'application/json')
      .send('{"bad"');
    expect(res.status).toBe(400);
    expect(res.body.error.code).toBe('invalid_json');
  });
});

describe('security', () => {
  it('sets helmet headers and hides x-powered-by', async () => {
    const res = await request(up()).get('/api/v1/health');
    expect(res.headers['x-powered-by']).toBeUndefined();
    expect(res.headers['x-content-type-options']).toBe('nosniff');
    expect(res.headers['content-security-policy']).toContain("default-src 'none'");
  });
  it('CORS allows the website and admin origins with credentials', async () => {
    for (const origin of ['http://localhost:5173', 'http://localhost:5180']) {
      const res = await request(up()).get('/api/v1/health').set('Origin', origin);
      expect(res.headers['access-control-allow-origin']).toBe(origin);
      expect(res.headers['access-control-allow-credentials']).toBe('true');
    }
  });
  it('CORS does not allow other origins', async () => {
    const res = await request(up()).get('/api/v1/health').set('Origin', 'https://evil.example');
    expect(res.headers['access-control-allow-origin']).toBeUndefined();
  });
  it('public GETs are cacheable for 5 minutes', async () => {
    const res = await request(up()).get('/api/v1/nope');
    expect(res.headers['cache-control']).toBe('public, max-age=300');
  });
});

describe('validate middleware', () => {
  const app = express();
  app.use(express.json());
  app.post(
    '/t',
    validate({
      body: z.object({
        name: z.string().min(1, 'Name is required'),
        email: z.string().email('Enter a valid email'),
      }),
      query: paginationQuery.extend({ sort: sortQuery.optional() }),
    }),
    (_req, res) => res.json(res.locals.valid),
  );
  app.use(errorHandler);

  it('returns field-level errors the admin UI can show', async () => {
    const res = await request(app).post('/t').send({ name: '', email: 'x' });
    expect(res.status).toBe(400);
    expect(res.body.error.code).toBe('validation_error');
    expect(res.body.error.details.fieldErrors).toEqual({
      name: ['Name is required'],
      email: ['Enter a valid email'],
    });
  });
  it('rejects unknown sort values and too-large pages', async () => {
    const res = await request(app).post('/t?sort=price&pageSize=500').send({ name: 'a', email: 'a@b.co' });
    expect(res.status).toBe(400);
    expect(Object.keys(res.body.error.details.fieldErrors).sort()).toEqual(['pageSize', 'sort']);
  });
  it('applies pagination defaults', async () => {
    const res = await request(app).post('/t').send({ name: 'a', email: 'a@b.co' });
    expect(res.status).toBe(200);
    expect(res.body.query).toEqual({ page: 1, pageSize: 10 });
  });
});
