import { assertEquals, assertExists } from 'jsr:@std/assert';
import { afterAll, beforeAll, describe, it } from 'jsr:@std/testing/bdd';
import { TypedRequest } from '@api.global/typedrequest';
import { createTestContainer, getTestPorts, loginAndGetIdentity, TEST_ADMIN_PASSWORD } from './helpers/server.helper.ts';
import { ObjectStorageContainer } from '../ts/index.ts';
import type * as interfaces from '../ts_interfaces/index.ts';
import type { IReq_AdminLoginWithUsernameAndPassword } from '../ts_interfaces/requests/admin.ts';
import type { IReq_VerifyIdentity } from '../ts_interfaces/requests/admin.ts';
import type { IReq_AdminLogout } from '../ts_interfaces/requests/admin.ts';
import type { IReq_GetServerStatus } from '../ts_interfaces/requests/status.ts';

const PORT_INDEX = 1;
const ports = getTestPorts(PORT_INDEX);
const url = `http://localhost:${ports.uiPort}/typedrequest`;

describe('Authentication', { sanitizeResources: false, sanitizeOps: false }, () => {
  let container: ObjectStorageContainer;
  let identity: interfaces.data.IIdentity;

  beforeAll(async () => {
    container = createTestContainer(PORT_INDEX);
    await container.start();
  });

  afterAll(async () => {
    await container.stop();
  });

  it('should login with valid credentials', async () => {
    identity = await loginAndGetIdentity(ports.uiPort);
    assertExists(identity.jwt);
    assertEquals(identity.userId, 'admin');
    assertEquals(identity.username, 'admin');
    assertEquals(identity.role, 'admin');
    assertEquals(identity.expiresAt > Date.now(), true);
  });

  it('should reject login with wrong password', async () => {
    const req = new TypedRequest<IReq_AdminLoginWithUsernameAndPassword>(
      url,
      'adminLoginWithUsernameAndPassword',
    );
    let threw = false;
    try {
      await req.fire({ username: 'admin', password: 'wrongpassword' });
    } catch {
      threw = true;
    }
    assertEquals(threw, true);
  });

  it('should reject login with wrong username', async () => {
    const req = new TypedRequest<IReq_AdminLoginWithUsernameAndPassword>(
      url,
      'adminLoginWithUsernameAndPassword',
    );
    let threw = false;
    try {
      await req.fire({ username: 'notadmin', password: TEST_ADMIN_PASSWORD });
    } catch {
      threw = true;
    }
    assertEquals(threw, true);
  });

  it('should verify a valid identity', async () => {
    const req = new TypedRequest<IReq_VerifyIdentity>(url, 'verifyIdentity');
    const response = await req.fire({ identity });
    assertEquals(response.valid, true);
    assertExists(response.identity);
    assertEquals(response.identity!.userId, 'admin');
  });

  it('should reject verification with tampered JWT', async () => {
    const req = new TypedRequest<IReq_VerifyIdentity>(url, 'verifyIdentity');
    const tamperedIdentity = { ...identity, jwt: identity.jwt + 'tampered' };
    const response = await req.fire({ identity: tamperedIdentity });
    assertEquals(response.valid, false);
  });

  it('should reject verification with missing identity', async () => {
    const req = new TypedRequest<IReq_VerifyIdentity>(url, 'verifyIdentity');
    const response = await req.fire({ identity: null as any });
    assertEquals(response.valid, false);
  });

  it('should logout successfully', async () => {
    const req = new TypedRequest<IReq_AdminLogout>(url, 'adminLogout');
    const response = await req.fire({ identity });
    assertEquals(response.ok, true);
  });

  it('should reject protected endpoint without identity', async () => {
    const req = new TypedRequest<IReq_GetServerStatus>(url, 'getServerStatus');
    let threw = false;
    try {
      await req.fire({ identity: null as any });
    } catch {
      threw = true;
    }
    assertEquals(threw, true);
  });
});
