import type { APIRoute } from 'astro';
import { env } from 'cloudflare:workers';
import {
  getCheckoutStatus,
  isOrderNotFoundError,
  type CheckoutDeps,
  type OrdersSchema,
} from '@platform-modules/commerce-checkout';
import { getDb, type DbEnv } from '../../../../lib/db.js';
import { getSession, type SessionEnv } from '../../../../lib/session.js';
import { jsonError, jsonOk } from '../../../../lib/http.js';

export const prerender = false;

type StatusEnv = SessionEnv & DbEnv;

export const GET: APIRoute = async ({ params, cookies }) => {
  const cfEnv = env as StatusEnv | undefined;
  if (!cfEnv?.SESSION) return jsonError(503, 'service_unavailable', 'Session store not configured.');
  if (!cfEnv?.DB && !cfEnv?.DATABASE_URL) return jsonError(503, 'service_unavailable', 'Database is not configured.');

  const session = await getSession(cfEnv, cookies);
  if (!session) return jsonError(401, 'unauthorized', 'Authentication required.');

  const { orderId } = params;
  if (!orderId) return jsonError(400, 'missing_param', 'orderId is required.');

  const { db } = getDb(cfEnv);
  const deps = { db } as unknown as CheckoutDeps<OrdersSchema>;

  try {
    const result = await getCheckoutStatus(deps, orderId, { userId: session.userId });
    return jsonOk(result);
  } catch (e) {
    if (isOrderNotFoundError(e)) return jsonError(404, 'order_not_found', `Order ${orderId} not found.`);
    return jsonError(500, 'internal_error', 'An unexpected error occurred.');
  }
};
