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

const fake = vi.hoisted(() => ({
  ref: null as null | ReturnType<typeof import('./helpers/fakeDb').createFakeDb>,
}));
vi.mock('../src/db/knex', async () => {
  const { createFakeDb: make } = await import('./helpers/fakeDb');
  fake.ref = make();
  return { db: fake.ref.db, pingDb: async () => true };
});

import { createApp } from '../src/app';
import { signToken } from '../src/lib/auth';

const ADMIN = {
  id: 1,
  name: 'Site admin',
  email: 'admin@bdmedicine.test',
  role: 'admin',
  status: 'active',
  last_login_at: null,
  password_hash: '',
};
const EDITOR = { ...ADMIN, id: 2, email: 'editor@bdmedicine.test', role: 'editor' };
const DISABLED = { ...ADMIN, id: 3, email: 'off@bdmedicine.test', status: 'disabled' };
const ORIGIN = 'http://localhost:5180';
const app = createApp({ ping: async () => true });
const cookieFor = (u: { id: number; role: string }) =>
  `bdm_admin=${signToken(String(u.id), u.role as 'admin')}`;

beforeAll(async () => {
  const hash = await bcrypt.hash('correct-horse-battery', 4);
  fake.ref!.tables.admins = [
    { ...ADMIN, password_hash: hash },
    { ...EDITOR, password_hash: hash },
    { ...DISABLED, password_hash: hash },
  ];
});

describe('POST /admin/auth/login', () => {
  it('validates the body with the shared zod schema', async () => {
    const res = await request(app)
      .post('/api/v1/admin/auth/login')
      .set('Origin', ORIGIN)
      .send({ email: 'x', password: '1', remember: true });
    expect(res.status).toBe(400);
    expect(Object.keys(res.body.error.details.fieldErrors).sort()).toEqual(['email', 'password']);
  });
  it('rejects a wrong password without saying which part was wrong', async () => {
    const res = await request(app)
      .post('/api/v1/admin/auth/login')
      .set('Origin', ORIGIN)
      .send({ email: ADMIN.email, password: 'wrong-password', remember: true });
    expect(res.status).toBe(401);
    expect(res.body.error).toEqual({
      code: 'invalid_credentials',
      message: 'Email or password is not correct.',
    });
  });
  it('rejects an unknown email with the same answer', async () => {
    const res = await request(app)
      .post('/api/v1/admin/auth/login')
      .set('Origin', ORIGIN)
      .send({ email: 'nobody@bdmedicine.test', password: 'whatever-password', remember: true });
    expect(res.status).toBe(401);
    expect(res.body.error.code).toBe('invalid_credentials');
  });
  it('blocks disabled accounts', async () => {
    const res = await request(app)
      .post('/api/v1/admin/auth/login')
      .set('Origin', ORIGIN)
      .send({ email: DISABLED.email, password: 'correct-horse-battery', remember: true });
    expect(res.status).toBe(403);
    expect(res.body.error.code).toBe('inactive');
  });
  it('sets an httpOnly SameSite=Lax cookie scoped to admin routes', async () => {
    const res = await request(app)
      .post('/api/v1/admin/auth/login')
      .set('Origin', ORIGIN)
      .send({ email: ADMIN.email, password: 'correct-horse-battery', remember: true });
    expect(res.status).toBe(200);
    expect(res.body.user).toMatchObject({ id: '1', email: ADMIN.email, role: 'admin', status: 'active' });
    expect(res.body.user.password_hash).toBeUndefined();
    const cookie = String(res.headers['set-cookie']);
    expect(cookie).toMatch(/bdm_admin=/);
    expect(cookie).toMatch(/HttpOnly/);
    expect(cookie).toMatch(/SameSite=Lax/);
    expect(cookie).toMatch(/Path=\/api\/v1\/admin/);
    expect(fake.ref!.calls.some((c) => c.table === 'audit_log' && c.op === 'insert')).toBe(true);
  });
});

describe('session + guards', () => {
  it('GET /auth/me without a cookie → 401', async () => {
    expect((await request(app).get('/api/v1/admin/auth/me')).status).toBe(401);
  });
  it('GET /auth/me with a valid cookie returns the user', async () => {
    const res = await request(app).get('/api/v1/admin/auth/me').set('Cookie', cookieFor(ADMIN));
    expect(res.status).toBe(200);
    expect(res.body.user.email).toBe(ADMIN.email);
  });
  it('a tampered token is rejected', async () => {
    const res = await request(app)
      .get('/api/v1/admin/auth/me')
      .set('Cookie', `${cookieFor(ADMIN)}x`);
    expect(res.status).toBe(401);
  });
  it('a disabled account loses access even with a valid token', async () => {
    expect((await request(app).get('/api/v1/admin/auth/me').set('Cookie', cookieFor(DISABLED))).status).toBe(
      401,
    );
  });
  it('state-changing requests from another origin are blocked (CSRF)', async () => {
    const res = await request(app)
      .post('/api/v1/admin/brands')
      .set('Cookie', cookieFor(ADMIN))
      .set('Origin', 'https://evil.example')
      .send({});
    expect(res.status).toBe(403);
  });
  it('editors cannot manage users or settings', async () => {
    expect((await request(app).get('/api/v1/admin/users').set('Cookie', cookieFor(EDITOR))).status).toBe(403);
    expect(
      (
        await request(app)
          .put('/api/v1/admin/settings')
          .set('Cookie', cookieFor(EDITOR))
          .set('Origin', ORIGIN)
          .send({})
      ).status,
    ).toBe(403);
  });
  it('logout clears the cookie', async () => {
    const res = await request(app).post('/api/v1/admin/auth/logout').set('Origin', ORIGIN);
    expect(res.status).toBe(204);
    expect(String(res.headers['set-cookie'])).toMatch(/bdm_admin=;/);
  });
});

describe('admin validation returns field errors the forms can show', () => {
  it('brand create: missing fields and a bad strength', async () => {
    const res = await request(app)
      .post('/api/v1/admin/brands')
      .set('Cookie', cookieFor(ADMIN))
      .set('Origin', ORIGIN)
      .send({ name: '', strength: 'lots', unitPrice: 1.5 });
    expect(res.status).toBe(400);
    const fe = res.body.error.details.fieldErrors;
    expect(fe.name).toEqual(['Brand name is required']);
    expect(fe.strength[0]).toMatch(/value and unit/);
    expect(fe.genericSlug).toBeDefined();
  });
  it('a price needs the DGDA date (cross-field rule from the shared schema)', async () => {
    const body = {
      name: 'Testopar',
      slug: 'testopar-250-mg-tablet',
      genericSlug: 'paracetamol',
      companySlug: 'square-pharmaceuticals',
      catalogue: 'human',
      form: 'Tablet',
      formIcon: 'tablet',
      strength: '250 mg',
      pack: '',
      unitPrice: 1.5,
      packPrice: null,
      priceUpdated: '',
      status: 'published',
      packImageUrl: '',
      packImageCredit: '',
      addedAt: '2026-11-26',
      formInfo: Object.fromEntries(
        [
          'indications',
          'dosage',
          'sideEffects',
          'precautions',
          'pregnancy',
          'contraindications',
          'interactions',
          'pharmacology',
          'overdose',
          'storage',
        ].map((k) => [k, { en: '', bn: '' }]),
      ),
    };
    const res = await request(app)
      .post('/api/v1/admin/brands')
      .set('Cookie', cookieFor(ADMIN))
      .set('Origin', ORIGIN)
      .send(body);
    expect(res.status).toBe(400);
    expect(res.body.error.details.fieldErrors.priceUpdated).toEqual([
      'Add the DGDA price date when a price is entered',
    ]);
  });
});

describe('R2 image uploads', () => {
  const presign = (body: object) =>
    request(app)
      .post('/api/v1/admin/images/presign')
      .set('Cookie', cookieFor(ADMIN))
      .set('Origin', ORIGIN)
      .send(body);
  it('only JPEG, PNG or WebP up to 5 MB', async () => {
    const res = await presign({ filename: 'a.gif', mime: 'image/gif', size: 6 * 1024 * 1024 });
    expect(res.status).toBe(400);
    expect(res.body.error.details.fieldErrors.mime).toEqual(['Use a JPEG, PNG or WebP image']);
    expect(res.body.error.details.fieldErrors.size).toEqual(['Image must be 5 MB or smaller']);
  });
  it('says clearly when R2 is not configured yet', async () => {
    const res = await presign({ filename: 'napa.jpg', mime: 'image/jpeg', size: 200_000 });
    expect(res.status).toBe(503);
    expect(res.body.error.code).toBe('storage_not_configured');
  });
  it('names files after the brand slug, one token for every size (Phase 10)', async () => {
    const { newKey, KEY_PATTERN } = await import('../src/lib/r2');
    const k = newKey('image/webp', { slug: 'napa-500-mg-tablet', token: 'k3x9q2ab', width: 800 });
    expect(k).toBe('brands/napa-500-mg-tablet-k3x9q2ab-800w.webp');
    expect(KEY_PATTERN.test(k)).toBe(true);
    expect(KEY_PATTERN.test(newKey('image/jpeg'))).toBe(true); // older shape still valid
    expect(
      KEY_PATTERN.test(newKey('image/webp', { folder: 'reviewers', slug: 'dr-a', token: 'abcdef12' })),
    ).toBe(true);
    for (const bad of [
      '../../x.webp',
      'brands/NAPA-abc123-800w.webp',
      'other/napa-abc123.webp',
      'brands/napa-abc123-800w.gif',
    ])
      expect(KEY_PATTERN.test(bad)).toBe(false);
  });
  it('confirm only accepts keys in the brands/yyyy/mm/uuid.ext pattern', async () => {
    const res = await request(app)
      .post('/api/v1/admin/images/confirm')
      .set('Cookie', cookieFor(ADMIN))
      .set('Origin', ORIGIN)
      .send({ key: '../../etc/passwd', credit: 'x' });
    expect(res.status).toBe(400);
    expect(res.body.error.details.fieldErrors.key).toEqual(['Invalid upload key']);
  });
});
