import { eq, sql } from 'drizzle-orm';
import { db } from '../../config/database.js';
import { outbox, type OutboxMessage, type NewOutboxMessage } from './outbox.schema.js';

type DbClient = typeof db;

export class OutboxRepository {
  async create(message: NewOutboxMessage, tx: DbClient = db): Promise<void> {
    await tx.insert(outbox).values(message);
  }

  async findPending(limit: number = 100): Promise<OutboxMessage[]> {
    return db
      .select()
      .from(outbox)
      .where(eq(outbox.status, 'pending'))
      .limit(limit);
  }

  async markProcessed(id: string): Promise<void> {
    await db
      .update(outbox)
      .set({ status: 'processed', processedAt: new Date() })
      .where(eq(outbox.id, id));
  }

  async incrementRetry(id: string): Promise<void> {
    await db
      .update(outbox)
      .set({ retryCount: sql`${outbox.retryCount} + 1` })
      .where(eq(outbox.id, id));
  }

  async markFailed(id: string): Promise<void> {
    await db
      .update(outbox)
      .set({ status: 'failed' })
      .where(eq(outbox.id, id));
  }
}

export const outboxRepository = new OutboxRepository();
