import assert from 'node:assert/strict';
import { readFileSync, readdirSync } from 'node:fs';
import { describe, it } from 'node:test';
import { detectLandingIntent } from './landingChatIntent.js';

describe('landing session schema access', () => {
  it('does not run owner-only index DDL from the API request path', () => {
    const serviceSource = readFileSync(new URL('./landingChatService.ts', import.meta.url), 'utf8');

    assert.doesNotMatch(serviceSource, /CREATE\s+INDEX/i);
  });

  it('grants the API role only the landing session data privileges it uses', () => {
    const migrationsDirectory = new URL('../../../../supabase/migrations/', import.meta.url);
    const migrationSql = readdirSync(migrationsDirectory)
      .filter(filename => filename.endsWith('.sql'))
      .map(filename => readFileSync(new URL(filename, migrationsDirectory), 'utf8'))
      .join('\n');

    assert.match(
      migrationSql,
      /GRANT\s+SELECT,\s*INSERT,\s*UPDATE\s+ON\s+(?:TABLE\s+)?(?:public\.)?landing_sessions\s+TO\s+postgres/i,
    );
  });
});

describe('detectLandingIntent', () => {
  it('routes console phrases (form on the right — not chat login)', () => {
    assert.equal(detectLandingIntent('sign in'), 'console');
    assert.equal(detectLandingIntent('I need to login'), 'console');
    assert.equal(detectLandingIntent('password'), 'console');
  });

  it('routes signup phrases', () => {
    assert.equal(detectLandingIntent('request access'), 'signup');
    assert.equal(detectLandingIntent('I want to sign up'), 'signup');
  });

  it('routes support phrases and longer free text', () => {
    assert.equal(detectLandingIntent('help'), 'support');
    assert.equal(detectLandingIntent('My VPN is broken again'), 'support');
  });

  it('returns null for short ambiguous replies', () => {
    assert.equal(detectLandingIntent('ok'), null);
    assert.equal(detectLandingIntent('yes'), null);
  });
});
