import {
  readRegistryCredential,
  removeRegistryCredential,
  saveRegistryCredential,
  type IRegistryCredential,
} from '../utils/auth-store.js';

export interface IAuthContextOptions {
  readonly cwd?: string;
  readonly registry?: string;
  readonly credentialsPath?: string;
}

export interface ILoginCommandOptions extends IAuthContextOptions {
  readonly username: string;
  readonly token: string;
  readonly email?: string;
  readonly expiresAt?: string;
}

export interface ILoginCommandResult {
  readonly registry: string;
  readonly username: string;
  readonly credentialsPath: string;
}

export interface ILogoutCommandResult {
  readonly registry: string;
  readonly removed: boolean;
  readonly credentialsPath: string;
}

export interface IWhoamiCommandResult {
  readonly registry: string;
  readonly authenticated: boolean;
  readonly username?: string;
  readonly email?: string;
  readonly expiresAt?: string;
}

export async function loginCommand(options: ILoginCommandOptions): Promise<ILoginCommandResult> {
  if (!options.username.trim()) {
    throw new Error('MX_AUTH_REQUIRED: username is required for login');
  }
  if (!options.token.trim()) {
    throw new Error('MX_AUTH_REQUIRED: token is required for login');
  }

  const cwd = options.cwd ?? process.cwd();
  const credential: IRegistryCredential = {
    username: options.username.trim(),
    token: options.token.trim(),
    email: options.email?.trim() || undefined,
    expiresAt: options.expiresAt?.trim() || undefined,
  };

  const { registry, credentialsPath } = saveRegistryCredential(cwd, credential, {
    registry: options.registry,
    credentialsPath: options.credentialsPath,
  });

  return {
    registry,
    username: credential.username,
    credentialsPath,
  };
}

export async function logoutCommand(options: IAuthContextOptions = {}): Promise<ILogoutCommandResult> {
  const cwd = options.cwd ?? process.cwd();
  return removeRegistryCredential(cwd, {
    registry: options.registry,
    credentialsPath: options.credentialsPath,
  });
}

export async function whoamiCommand(options: IAuthContextOptions = {}): Promise<IWhoamiCommandResult> {
  const cwd = options.cwd ?? process.cwd();
  const { registry, credential } = readRegistryCredential(cwd, {
    registry: options.registry,
    credentialsPath: options.credentialsPath,
  });

  if (!credential) {
    return { registry, authenticated: false };
  }

  return {
    registry,
    authenticated: true,
    username: credential.username,
    email: credential.email,
    expiresAt: credential.expiresAt,
  };
}
