import { S3Client, GetObjectCommand, PutObjectCommand } from "@aws-sdk/client-s3";
import { sql } from "@/db";
import { nanoid } from "nanoid";
import sharp from "sharp";

function getR2Config() {
  return {
    accountId: process.env.R2_ACCOUNT_ID!,
    accessKeyId: process.env.R2_ACCESS_KEY_ID!,
    secretKey: process.env.R2_SECRET_ACCESS_KEY!,
    bucket: process.env.R2_BUCKET_NAME!,
  };
}

export async function generateThumbnail(memoryId: string): Promise<void> {
  const rows = await sql`SELECT id, family_id, r2_key FROM memories WHERE id = ${memoryId} LIMIT 1`;
  const memory = rows[0];
  if (!memory) throw new Error(`Memory not found: ${memoryId}`);

  const R2 = getR2Config();
  const client = new S3Client({
    region: "auto",
    endpoint: `https://${R2.accountId}.r2.cloudflarestorage.com`,
    credentials: { accessKeyId: R2.accessKeyId, secretAccessKey: R2.secretKey },
  });

  // Download original
  const getCmd = new GetObjectCommand({ Bucket: R2.bucket, Key: memory.r2_key });
  const response = await client.send(getCmd);
  const chunks: Buffer[] = [];
  for await (const chunk of response.Body as AsyncIterable<Buffer>) {
    chunks.push(chunk);
  }
  const original = Buffer.concat(chunks);

  // Generate thumbnail with sharp: max 400px, WebP quality 60
  const thumbBuffer = await sharp(original)
    .resize(400, 400, { fit: "inside", withoutEnlargement: true })
    .webp({ quality: 60 })
    .toBuffer();

  // Upload thumbnail
  const thumbKey = `families/${memory.family_id}/thumbnails/${nanoid(12)}.webp`;
  await client.send(new PutObjectCommand({
    Bucket: R2.bucket,
    Key: thumbKey,
    Body: thumbBuffer,
    ContentType: "image/webp",
  }));

  // Update DB
  await sql`UPDATE memories SET r2_thumbnail_key = ${thumbKey}, updated_at = now() WHERE id = ${memoryId}`;
}
