import type pg from 'pg';

export type PaymentMethodKind = 'cash' | 'card' | 'other';

export interface PosPaymentMethodRepository {
  listByStore(storeId: string): Promise<PosPaymentMethod[]>;
}

export interface PosPaymentMethod {
  id: string;
  storeId: string;
  code: string;
  label: string;
  kind: PaymentMethodKind;
  active: boolean;
  sortOrder: number;
  config: Record<string, unknown>;
  createdAt: Date;
  updatedAt: Date;
}

interface PaymentMethodRow {
  id: string;
  store_id: string;
  code: string;
  label: string;
  kind: PaymentMethodKind;
  active: boolean;
  sort_order: number;
  config: Record<string, unknown>;
  created_at: Date;
  updated_at: Date;
}

function toPaymentMethod(row: PaymentMethodRow): PosPaymentMethod {
  return {
    id: row.id,
    storeId: row.store_id,
    code: row.code,
    label: row.label,
    kind: row.kind,
    active: row.active,
    sortOrder: row.sort_order,
    config: row.config,
    createdAt: row.created_at,
    updatedAt: row.updated_at,
  };
}

export class PgPaymentMethodRepository implements PosPaymentMethodRepository {
  constructor(private readonly pool: pg.Pool) {}

  async listByStore(storeId: string): Promise<PosPaymentMethod[]> {
    const result = await this.pool.query<PaymentMethodRow>(
      'SELECT * FROM pos_payment_methods WHERE store_id = $1 AND active = true ORDER BY sort_order',
      [storeId],
    );
    return result.rows.map(toPaymentMethod);
  }
}
