import { describe, it, expect } from 'vitest';

const BASE = process.env.TEST_BASE_URL ?? 'http://localhost:8000';
const ADMIN_USER = process.env.AUTH_ADMIN_USERNAME ?? 'admin';
const ADMIN_PASS = process.env.AUTH_ADMIN_PASSWORD ?? 'admin';

describe('Auth + basic API', () => {
  it('POST /api/auth/login then GET /api/auth/me', async () => {
    const loginRes = await fetch(`${BASE}/api/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username: ADMIN_USER, password: ADMIN_PASS }),
    });

    expect(loginRes.status).toBeGreaterThanOrEqual(200);
    expect(loginRes.status).toBeLessThan(300);

    const loginBody = await loginRes.json();
    expect(loginBody).toBeDefined();
    expect(loginBody.token).toBeTruthy();

    const token = loginBody.token as string;

    const meRes = await fetch(`${BASE}/api/auth/me`, {
      headers: { Authorization: `Bearer ${token}` },
    });

    expect(meRes.status).toBe(200);
    const meBody = await meRes.json();
    expect(meBody).toBeDefined();
    // may return { user } or user object depending on implementation
    if (meBody.user) {
      expect(meBody.user.username ?? meBody.user.email).toBeTruthy();
    } else {
      expect(meBody.username ?? meBody.email).toBeTruthy();
    }
  });

  it('GET /api/employes returns list', async () => {
    const loginRes = await fetch(`${BASE}/api/auth/login`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ username: ADMIN_USER, password: ADMIN_PASS }),
    });

    expect(loginRes.status).toBeGreaterThanOrEqual(200);
    expect(loginRes.status).toBeLessThan(300);

    const loginBody = await loginRes.json();
    const res = await fetch(`${BASE}/api/employes`, {
      headers: { Authorization: `Bearer ${loginBody.token as string}` },
    });
    expect(res.status).toBe(200);
    const body = await res.json();
    // support both { items: [] } and plain array
    const items = Array.isArray(body) ? body : body.items ?? body;
    expect(Array.isArray(items)).toBeTruthy();
  });
});
