import { eq } from 'drizzle-orm'
import type { Querier } from '@platform-modules/db'
import { ReviewNotFoundError } from './errors.js'
import { assertReviewId } from './ids.js'
import { review, type ReviewsSchema } from './schema.js'
import type { ReviewStatus } from './types.js'

function actionToStatus(action: 'approve' | 'reject'): ReviewStatus {
  return action === 'approve' ? 'approved' : 'rejected'
}

export async function moderateReview(
  q: Querier<ReviewsSchema>,
  reviewId: string,
  action: 'approve' | 'reject',
): Promise<void> {
  // D9: validate the untrusted reviewId at the boundary BEFORE it reaches the
  // uuid column — a non-uuid id otherwise raises a raw Postgres error (info-leak).
  assertReviewId(reviewId)

  const status = actionToStatus(action)
  const now = new Date()

  const [updated] = await q
    .update(review)
    .set({ status, updatedAt: now })
    .where(eq(review.id, reviewId))
    .returning()

  if (!updated) {
    throw new ReviewNotFoundError(reviewId)
  }
}
