import { DeleteObjectCommand, HeadObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { env } from '../config/env';
import { HttpError } from './http-errors';

/** Cloudflare R2 (S3 API). Files go browser → R2 directly via presigned PUT; they never pass through this server. */
export const ALLOWED_MIME = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp' } as const;
export const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
export const PRESIGN_TTL_SEC = 300;

let client: S3Client | null = null;
export function r2() {
  if (
    !env.R2_ACCOUNT_ID ||
    !env.R2_ACCESS_KEY_ID ||
    !env.R2_SECRET_ACCESS_KEY ||
    !env.R2_BUCKET ||
    !env.R2_PUBLIC_URL
  ) {
    throw new HttpError(
      503,
      'storage_not_configured',
      'Image storage is not configured yet (R2_* environment variables).',
    );
  }
  client ??= new S3Client({
    region: 'auto',
    endpoint: `https://${env.R2_ACCOUNT_ID}.r2.cloudflarestorage.com`,
    credentials: { accessKeyId: env.R2_ACCESS_KEY_ID, secretAccessKey: env.R2_SECRET_ACCESS_KEY },
    requestChecksumCalculation: 'WHEN_REQUIRED',
    responseChecksumValidation: 'WHEN_REQUIRED',
  });
  return { client, bucket: env.R2_BUCKET, publicUrl: env.R2_PUBLIC_URL.replace(/\/$/, '') };
}

/** Long browser/CDN cache for uploaded images: a new upload always gets a new file name. */
export const IMAGE_CACHE_CONTROL = 'public, max-age=31536000, immutable';

/**
 * Upload keys (SEO Phase 10). With a slug, the file is named after the page it belongs to:
 *   brands/napa-500-mg-tablet-k3x9q2-800w.webp      (token shared by the 200/400/800 sizes of one upload)
 * Without one (older uploads): brands/{yyyy}/{mm}/{uuid}.{ext}
 */
export function newKey(
  mime: keyof typeof ALLOWED_MIME,
  opts: { folder?: 'brands' | 'reviewers' | 'generics'; slug?: string; token?: string; width?: number } = {},
  now = new Date(),
) {
  const ext = ALLOWED_MIME[mime];
  const folder = opts.folder ?? 'brands';
  if (opts.slug) {
    const token = opts.token ?? crypto.randomUUID().slice(0, 8);
    return `${folder}/${opts.slug}-${token}${opts.width ? `-${opts.width}w` : ''}.${ext}`;
  }
  const mm = String(now.getUTCMonth() + 1).padStart(2, '0');
  return `${folder}/${now.getUTCFullYear()}/${mm}/${crypto.randomUUID()}.${ext}`;
}

/** Both key shapes; nothing else (no "..", no other folders). */
export const KEY_PATTERN =
  /^(brands|reviewers|generics)\/(\d{4}\/\d{2}\/[0-9a-f-]{36}|[a-z0-9]+(?:-[a-z0-9]+)*-(?:structure|[a-z0-9]{6,12}(?:-\d{2,4}w)?))\.(jpg|png|webp)$/;

export async function presignPut(key: string, mime: string, size: number) {
  const { client: c, bucket, publicUrl } = r2();
  const uploadUrl = await getSignedUrl(
    c,
    // the browser must send the same Content-Type and Cache-Control headers with its PUT
    new PutObjectCommand({
      Bucket: bucket,
      Key: key,
      ContentType: mime,
      ContentLength: size,
      CacheControl: IMAGE_CACHE_CONTROL,
    }),
    { expiresIn: PRESIGN_TTL_SEC },
  );
  return {
    uploadUrl,
    key,
    publicUrl: `${publicUrl}/${key}`,
    headers: { 'Cache-Control': IMAGE_CACHE_CONTROL },
  };
}

export async function headObject(key: string) {
  const { client: c, bucket } = r2();
  try {
    const h = await c.send(new HeadObjectCommand({ Bucket: bucket, Key: key }));
    return { size: Number(h.ContentLength ?? 0), mime: h.ContentType ?? '' };
  } catch {
    return null;
  }
}

export async function deleteObject(key: string) {
  const { client: c, bucket } = r2();
  await c.send(new DeleteObjectCommand({ Bucket: bucket, Key: key }));
}

export async function putObject(key: string, body: Buffer, mime: string) {
  const { client: c, bucket, publicUrl } = r2();
  await c.send(
    new PutObjectCommand({
      Bucket: bucket,
      Key: key,
      Body: body,
      ContentType: mime,
      CacheControl: IMAGE_CACHE_CONTROL,
    }),
  );
  return `${publicUrl}/${key}`;
}
