import type pg from 'pg';
import type { OrderItemVerifier } from '../domain/ports.js';

/**
 * Verifies that an order item is delivered and owned by the user. Order items
 * are considered delivered when their order state is DELIVERED.
 */
export class PgOrderItemVerifier implements OrderItemVerifier {
  constructor(private readonly pool: pg.Pool) {}

  async isDeliveredForUser(userId: string, orderItemId: string): Promise<boolean> {
    const result = await this.pool.query<{ exists: boolean }>(
      `SELECT EXISTS (
         SELECT 1 FROM orders_items oi
         JOIN orders_orders oo ON oo.id = oi.order_id
         WHERE oi.id = $1 AND oo.user_id = $2 AND oo.state = 'DELIVERED'
       ) AS exists`,
      [orderItemId, userId],
    );
    return result.rows[0]?.exists ?? false;
  }
}
