import { test, expect } from '@playwright/test';

test.describe('Legacy CSV Data Import Wizard (FR-SMS3 E2E)', () => {
  let adminToken: string;

  test.beforeAll(async ({ request }) => {
    const response = await request.post('/api/auth/login', {
      data: { email: 'admin@school.com', password: 'admin123' }
    });
    expect(response.ok()).toBeTruthy();
    const body = await response.json();
    adminToken = body.token;
  });

  test('1. API preview returns headers and row diagnostics for valid CSV payload', async ({ request }) => {
    const csvContent = `First Name,Last Name,Email,Class,Parent Name,Parent Phone
Nyarai,Takawira,nyarai.t.${Date.now()}@testschool.co.zw,Form 3 East,Blessing Takawira,0775554444
Tinashe,Gumbo,tinashe.g.${Date.now()}@testschool.co.zw,Form 3 East,Farai Gumbo,0776663333`;

    const res = await request.post('/api/students/import/preview', {
      headers: { Authorization: `Bearer ${adminToken}` },
      data: { csvContent }
    });

    expect(res.ok()).toBeTruthy();
    const data = await res.json();
    expect(data.success).toBe(true);
    expect(data.total_rows).toBe(2);
    expect(data.valid_rows_count).toBe(2);
    expect(data.headers).toContain('First Name');
  });

  test('2. API commit executes transactional import creating students and parent links', async ({ request }) => {
    const csvContent = `First Name,Last Name,Email,Class,Parent Name,Parent Phone
Kudakwashe,Banda,kuda.b.${Date.now()}@testschool.co.zw,Form 2 South,Mercy Banda,0771110000`;

    const res = await request.post('/api/students/import/commit', {
      headers: { Authorization: `Bearer ${adminToken}` },
      data: {
        csvContent,
        options: { autoCreateClasses: true }
      }
    });

    expect(res.ok()).toBeTruthy();
    const data = await res.json();
    expect(data.success).toBe(true);
    expect(data.inserted_students).toBe(1);
    expect(data.linked_parents).toBe(1);
  });

  test('3. Non-admin roles are forbidden from invoking legacy import endpoints', async ({ request }) => {
    const studentLogin = await request.post('/api/auth/login', {
      data: { email: 'student@school.com', password: 'student123' }
    });
    const { token: studentToken } = await studentLogin.json();

    const res = await request.post('/api/students/import/preview', {
      headers: { Authorization: `Bearer ${studentToken}` },
      data: { csvContent: 'First Name,Last Name\nJohn,Doe' }
    });

    expect(res.status()).toBe(403);
  });
});
