/**
 * Security: Input Sanitization & File Upload Validation
 *
 * Documents the security boundary between Zod schema validation and the
 * parameterized-query layer (Drizzle ORM).
 *
 * Key principle from SECURITY-GUIDELINES.md:
 *   SQL injection is prevented by Drizzle's parameterized queries ($1 placeholders),
 *   NOT by filtering characters out of input.  These tests confirm:
 *     (a) Zod schemas pass injection payloads as plain strings (correct behaviour).
 *     (b) File upload constants enforce the MIME-type allowlist and 50 MB cap.
 */
import { describe, expect, it } from 'vitest';

// ─────────────────────────────────────────────────────────────────────────────

describe('SQL injection prevention via Zod schemas', () => {
  it('createClientSchema accepts SQL injection payload as plain string (parameterized queries handle it)', async () => {
    const { createClientSchema } = await import('@/lib/validators/clients');
    const result = createClientSchema.safeParse({
      fullName: "Robert'); DROP TABLE clients;--",
      contacts: [{ channel: 'email', value: 'test@example.com' }],
    });
    // Zod must accept this as a valid string - we rely on Drizzle for SQL safety
    expect(result.success).toBe(true);
    if (result.success) {
      // The payload passes through unchanged; the query layer uses $1 placeholders
      expect(result.data.fullName).toBe("Robert'); DROP TABLE clients;--");
    }
  });

  it('createClientSchema accepts UNION-based injection as plain text', async () => {
    const { createClientSchema } = await import('@/lib/validators/clients');
    const result = createClientSchema.safeParse({
      fullName: "' UNION SELECT table_name FROM information_schema.tables--",
      contacts: [{ channel: 'phone', value: '+61400000000' }],
    });
    expect(result.success).toBe(true);
  });

  it('createClientSchema rejects empty fullName (business rule, not injection defence)', async () => {
    const { createClientSchema } = await import('@/lib/validators/clients');
    const result = createClientSchema.safeParse({
      fullName: '',
      contacts: [{ channel: 'email', value: 'test@example.com' }],
    });
    expect(result.success).toBe(false);
  });

  it('createClientSchema rejects when contacts array is empty', async () => {
    const { createClientSchema } = await import('@/lib/validators/clients');
    const result = createClientSchema.safeParse({
      fullName: 'John Smith',
      contacts: [],
    });
    expect(result.success).toBe(false);
  });

  it('searchQuerySchema accepts injection payload with length ≥ 2 (parameterized query handles it)', async () => {
    const { searchQuerySchema } = await import('@/lib/validators/search');
    const result = searchQuerySchema.safeParse({
      q: "'; DROP TABLE clients;--",
    });
    // Min length 2, so this passes - Drizzle uses $1 for the actual query
    expect(result.success).toBe(true);
  });

  it('searchQuerySchema rejects single-char input (below min length)', async () => {
    const { searchQuerySchema } = await import('@/lib/validators/search');
    const result = searchQuerySchema.safeParse({ q: "'" });
    expect(result.success).toBe(false);
  });

  it('searchQuerySchema rejects empty query string', async () => {
    const { searchQuerySchema } = await import('@/lib/validators/search');
    const result = searchQuerySchema.safeParse({ q: '' });
    expect(result.success).toBe(false);
  });

  it('searchQuerySchema enforces max length of 200', async () => {
    const { searchQuerySchema } = await import('@/lib/validators/search');
    const result = searchQuerySchema.safeParse({ q: 'a'.repeat(201) });
    expect(result.success).toBe(false);
  });

  it('createClientSchema enforces fullName max length of 200', async () => {
    const { createClientSchema } = await import('@/lib/validators/clients');
    const result = createClientSchema.safeParse({
      fullName: 'x'.repeat(201),
      contacts: [{ channel: 'email', value: 'test@example.com' }],
    });
    expect(result.success).toBe(false);
  });
});

// ─────────────────────────────────────────────────────────────────────────────

describe('File upload validation - MIME type allowlist', () => {
  it('rejects application/x-executable (binary/shellcode)', async () => {
    const { ALLOWED_MIME_TYPES } = await import('@/lib/constants/file-validation');
    expect(ALLOWED_MIME_TYPES.has('application/x-executable')).toBe(false);
  });

  it('rejects text/html (XSS vector)', async () => {
    const { ALLOWED_MIME_TYPES } = await import('@/lib/constants/file-validation');
    expect(ALLOWED_MIME_TYPES.has('text/html')).toBe(false);
  });

  it('rejects application/javascript (script injection)', async () => {
    const { ALLOWED_MIME_TYPES } = await import('@/lib/constants/file-validation');
    expect(ALLOWED_MIME_TYPES.has('application/javascript')).toBe(false);
  });

  it('rejects application/x-sh (shell script)', async () => {
    const { ALLOWED_MIME_TYPES } = await import('@/lib/constants/file-validation');
    expect(ALLOWED_MIME_TYPES.has('application/x-sh')).toBe(false);
  });

  it('rejects application/octet-stream (generic binary)', async () => {
    const { ALLOWED_MIME_TYPES } = await import('@/lib/constants/file-validation');
    expect(ALLOWED_MIME_TYPES.has('application/octet-stream')).toBe(false);
  });

  it('rejects image/svg+xml (SVG can embed scripts)', async () => {
    const { ALLOWED_MIME_TYPES } = await import('@/lib/constants/file-validation');
    expect(ALLOWED_MIME_TYPES.has('image/svg+xml')).toBe(false);
  });

  it('allows application/pdf', async () => {
    const { ALLOWED_MIME_TYPES } = await import('@/lib/constants/file-validation');
    expect(ALLOWED_MIME_TYPES.has('application/pdf')).toBe(true);
  });

  it('allows image/jpeg', async () => {
    const { ALLOWED_MIME_TYPES } = await import('@/lib/constants/file-validation');
    expect(ALLOWED_MIME_TYPES.has('image/jpeg')).toBe(true);
  });

  it('allows image/png', async () => {
    const { ALLOWED_MIME_TYPES } = await import('@/lib/constants/file-validation');
    expect(ALLOWED_MIME_TYPES.has('image/png')).toBe(true);
  });

  it('allows image/webp', async () => {
    const { ALLOWED_MIME_TYPES } = await import('@/lib/constants/file-validation');
    expect(ALLOWED_MIME_TYPES.has('image/webp')).toBe(true);
  });

  it('allows common office document types', async () => {
    const { ALLOWED_MIME_TYPES } = await import('@/lib/constants/file-validation');
    expect(ALLOWED_MIME_TYPES.has('application/msword')).toBe(true);
    expect(
      ALLOWED_MIME_TYPES.has(
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
      ),
    ).toBe(true);
    expect(ALLOWED_MIME_TYPES.has('application/vnd.ms-excel')).toBe(true);
    expect(
      ALLOWED_MIME_TYPES.has('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'),
    ).toBe(true);
  });

  it('allows text/plain and text/csv', async () => {
    const { ALLOWED_MIME_TYPES } = await import('@/lib/constants/file-validation');
    expect(ALLOWED_MIME_TYPES.has('text/plain')).toBe(true);
    expect(ALLOWED_MIME_TYPES.has('text/csv')).toBe(true);
  });
});

describe('File upload validation - size limit', () => {
  it('MAX_FILE_SIZE is exactly 50 MB (52_428_800 bytes)', async () => {
    const { MAX_FILE_SIZE } = await import('@/lib/constants/file-validation');
    expect(MAX_FILE_SIZE).toBe(50 * 1024 * 1024);
    expect(MAX_FILE_SIZE).toBe(52_428_800);
  });

  it('a 50 MB file is within the allowed limit', async () => {
    const { MAX_FILE_SIZE } = await import('@/lib/constants/file-validation');
    const fiftyMb = 50 * 1024 * 1024;
    expect(fiftyMb).toBeLessThanOrEqual(MAX_FILE_SIZE);
  });

  it('a 50 MB + 1 byte file exceeds the limit', async () => {
    const { MAX_FILE_SIZE } = await import('@/lib/constants/file-validation');
    const overLimit = 50 * 1024 * 1024 + 1;
    expect(overLimit).toBeGreaterThan(MAX_FILE_SIZE);
  });
});
