import { HttpException, HttpStatus } from '@nestjs/common';
import { describeApiCode } from '@pac/types';

/**
 * Business-level error carrying an explicit 5-digit ApiCode.
 *
 * Throw this anywhere a domain-specific error is needed. The exception filter
 * unwraps it and emits the wrapped response { code, msg, data: null, details? }.
 *
 * HTTP status is forced to 200 (we always return 200 for known outcomes;
 * only genuine server crashes return 5xx). The 200 here is a marker — the
 * actual status code is set by the filter, not by Nest.
 *
 * Usage:
 *   throw new BizError(ApiCode.PLAN_NOT_FOUND, `Plan ${id} not found`);
 *   throw new BizError(ApiCode.PLAN_ALREADY_ASSIGNED);  // uses default msg
 *   throw new BizError(ApiCode.AUTH_INVALID_CREDENTIALS, 'msg', { hint: '...' });
 */
export class BizError extends HttpException {
  readonly code: number;
  readonly msg: string;
  readonly details?: unknown;

  constructor(code: number, msg?: string, details?: unknown) {
    const finalMsg = msg ?? describeApiCode(code);
    super({ code, msg: finalMsg, details }, HttpStatus.OK);
    this.code = code;
    this.msg = finalMsg;
    this.details = details;
  }
}
