import { describe, expect, it, vi } from 'vitest';
import request from 'supertest';

vi.mock('../src/db/knex', () => ({ db: {}, pingDb: async () => true }));
vi.mock('../src/modules/public/browse', async (orig) => ({
  ...(await orig<object>()),
  saveContact: vi.fn(async () => undefined),
}));

import { createApp } from '../src/app';
const app = createApp({ ping: async () => true });

describe('public request validation', () => {
  it('live search needs 2+ characters', async () => {
    const res = await request(app).get('/api/v1/search/suggest?q=n');
    expect(res.status).toBe(400);
    expect(res.body.error.details.fieldErrors.q).toEqual(['Type at least 2 characters']);
  });
  it('unknown sort values are rejected (whitelist)', async () => {
    const res = await request(app).get('/api/v1/generics/paracetamol/brands?sort=price');
    expect(res.status).toBe(400);
    expect(res.body.error.details.fieldErrors.sort).toBeDefined();
  });
  it('letters must be a–z and slugs must be slugs', async () => {
    expect((await request(app).get('/api/v1/medicines?letter=ab')).status).toBe(400);
    expect((await request(app).get('/api/v1/medicines/Bad_Slug')).status).toBe(400);
  });
  it('page size is capped at 50', async () => {
    expect((await request(app).get('/api/v1/medicines?letter=a&pageSize=51')).status).toBe(400);
  });
});

describe('POST /contact', () => {
  const ok = {
    contact: 'someone@example.com',
    topic: 'mistake',
    message: 'Pack size looks wrong',
    ref: 'napa-500-mg-suppository',
  };
  it('accepts a valid message', async () => {
    expect((await request(app).post('/api/v1/contact').send(ok)).status).toBe(201);
  });
  it('rejects the honeypot field (bots fill it)', async () => {
    const res = await request(app)
      .post('/api/v1/contact')
      .send({ ...ok, website: 'http://spam.example' });
    expect(res.status).toBe(400);
  });
  it('returns field errors for the form', async () => {
    const res = await request(app).post('/api/v1/contact').send({ topic: 'other', message: '' });
    expect(res.body.error.details.fieldErrors.contact).toEqual([
      'Please add an email or phone number so we can reply.',
    ]);
    expect(res.body.error.details.fieldErrors.message).toEqual(['Please write a short message.']);
  });
});
