import { getQuery } from 'h3';
import {
  fetchTransactions,
  type TransactionStatus,
} from '~/utils/finance-repository';
import { useResponseSuccess } from '~/utils/response';

const DEFAULT_STATUSES: TransactionStatus[] = [
  'draft',
  'pending',
  'approved',
  'rejected',
  'paid',
];

export default defineEventHandler(async (event) => {
  const query = getQuery(event);
  const includeDeleted = query.includeDeleted === 'true';
  const type = query.type as string | undefined;
  const rawStatuses = (query.statuses ?? query.status) as string | undefined;
  const statuses = rawStatuses
    ? (rawStatuses
        .split(',')
        .map((item) => item.trim())
        .filter((item) => item.length > 0) as TransactionStatus[])
    : DEFAULT_STATUSES;

  const reimbursements = fetchTransactions({
    includeDeleted,
    type,
    statuses,
  });

  return useResponseSuccess(reimbursements);
});
