import { ObjectStorageContainer } from '../../ts/index.ts';
import type { IObjectStorageConfig } from '../../ts/types.ts';
import type * as interfaces from '../../ts_interfaces/index.ts';
import { TypedRequest } from '@api.global/typedrequest';
import type { IReq_AdminLoginWithUsernameAndPassword } from '../../ts_interfaces/requests/admin.ts';

export const TEST_ADMIN_PASSWORD = 'testpassword';
export const TEST_ACCESS_KEY = 'testkey';
export const TEST_SECRET_KEY = 'testsecret';

export function getTestPorts(index: number): { objstPort: number; uiPort: number } {
  return {
    objstPort: 19000 + index * 10,
    uiPort: 19001 + index * 10,
  };
}

export function createTestContainer(
  index: number,
  extraConfig?: Partial<IObjectStorageConfig>,
): ObjectStorageContainer {
  const ports = getTestPorts(index);
  return new ObjectStorageContainer({
    objstPort: ports.objstPort,
    uiPort: ports.uiPort,
    storageDirectory: `.nogit/testdata-${index}`,
    accessCredentials: [{ accessKeyId: TEST_ACCESS_KEY, secretAccessKey: TEST_SECRET_KEY }],
    adminPassword: TEST_ADMIN_PASSWORD,
    region: 'us-east-1',
    ...extraConfig,
  });
}

export async function loginAndGetIdentity(
  uiPort: number,
): Promise<interfaces.data.IIdentity> {
  const req = new TypedRequest<IReq_AdminLoginWithUsernameAndPassword>(
    `http://localhost:${uiPort}/typedrequest`,
    'adminLoginWithUsernameAndPassword',
  );
  const response = await req.fire({
    username: 'admin',
    password: TEST_ADMIN_PASSWORD,
  });
  if (!response.identity) {
    throw new Error('Login failed: no identity returned');
  }
  return response.identity;
}
