import { createDbService } from '@/server/services/db.js';
import { eq } from 'drizzle-orm';
import { platformImageLimits } from '@/server/db/schema.js';
import { updatePlatformImageLimits as persistPlatformImageLimits } from '@/server/db/queries/image-limits.js';
import {
  DEFAULT_MAX_PER_DEAL,
  DEFAULT_MAX_PER_SKU,
  MAX_PER_DEAL_CAP_HARD,
  MAX_PER_SKU_CAP_HARD,
} from '@/server/constants/image-limits.js';

export type PlatformImageLimits = {
  maxImagesPerDeal: number;
  maxImagesPerSku: number;
};

export async function getPlatformImageLimits(env: {
  DATABASE_URL: string;
}): Promise<PlatformImageLimits> {
  const db = createDbService(env);
  const rows = await db
    .select({
      maxImagesPerDeal: platformImageLimits.maxImagesPerDeal,
      maxImagesPerSku: platformImageLimits.maxImagesPerSku,
    })
    .from(platformImageLimits)
    .where(eq(platformImageLimits.id, 1))
    .limit(1);

  const row = rows[0];
  if (!row) {
    return { maxImagesPerDeal: DEFAULT_MAX_PER_DEAL, maxImagesPerSku: DEFAULT_MAX_PER_SKU };
  }
  return row;
}

export async function updatePlatformImageLimits(
  env: { DATABASE_URL: string },
  next: PlatformImageLimits,
  userId: string,
): Promise<PlatformImageLimits> {
  if (
    !Number.isInteger(next.maxImagesPerDeal) ||
    !Number.isInteger(next.maxImagesPerSku) ||
    next.maxImagesPerDeal < 1 ||
    next.maxImagesPerDeal > MAX_PER_DEAL_CAP_HARD ||
    next.maxImagesPerSku < 1 ||
    next.maxImagesPerSku > MAX_PER_SKU_CAP_HARD
  ) {
    throw new Error('image limits out of bounds');
  }
  const db = createDbService(env);
  await persistPlatformImageLimits(db, next, userId);
  return next;
}
