const fs = require('fs');
const path = require('path');

const sql = fs.readFileSync(
  path.join(__dirname, '../../supabase/migrations/002_line_movement.sql'),
  'utf8'
);

describe('Migration 002 — Line Movement', () => {
  test('creates line_baselines table', () => {
    expect(sql).toContain('CREATE TABLE public.line_baselines');
  });

  test('creates line_movements table', () => {
    expect(sql).toContain('CREATE TABLE public.line_movements');
  });

  test('creates cascade_alerts table', () => {
    expect(sql).toContain('CREATE TABLE public.cascade_alerts');
  });

  test('line_movements has direction constraint', () => {
    expect(sql).toMatch(/direction.*CHECK.*\(direction IN \('up',\s*'down'\)\)/);
  });

  test('cascade_alerts has alert_type constraint', () => {
    expect(sql).toMatch(/alert_type.*CHECK.*\(alert_type IN/);
  });

  test('cascade_alerts has RLS enabled', () => {
    expect(sql).toContain('ALTER TABLE public.cascade_alerts ENABLE ROW LEVEL SECURITY');
  });

  test('cascade_alerts has select and update policies', () => {
    expect(sql).toContain('CREATE POLICY "alerts_select_own"');
    expect(sql).toContain('CREATE POLICY "alerts_update_own"');
  });

  test('unique index on baselines prevents duplicates', () => {
    expect(sql).toContain('CREATE UNIQUE INDEX idx_baseline_unique');
  });

  test('cleanup function exists', () => {
    expect(sql).toContain('CREATE OR REPLACE FUNCTION public.cleanup_old_baselines');
  });
});
