import { randomUUID } from 'node:crypto';
import type { BlogMedia } from '@prisma/client';
import { prismaUnscoped as db } from '../../lib/prisma';
import { BadRequestError, ConflictError, NotFoundError } from '../../lib/errors';
import { BLOG_MEDIA_PREFIX, deleteBlogObject, presignBlogObject, putBlogObject } from '../uploads/uploads.service';
import { mediaPath } from './blog-rules';

/**
 * The blog's image library (docs/blog-cms-plan.md, B1).
 *
 * Images stay private in S3 under platform/website-blog/. The editor sees them
 * through short-lived links; the website build downloads them, converts them
 * to WebP and serves them itself as /assets/blog/cms/<id>.webp, which is also
 * how a post's Markdown refers to them.
 */

export const MEDIA_MAX_BYTES = 5 * 1024 * 1024;

/** S3, behind one object so the tests can stand in for it. */
export const storage = { put: putBlogObject, presign: presignBlogObject, remove: deleteBlogObject };
const MIN_SIDE = 100;
const MAX_SIDE = 10_000;

type ImageType = { mime: 'image/jpeg' | 'image/png' | 'image/webp'; ext: 'jpg' | 'png' | 'webp' };

/** The type from the bytes themselves, never from the name or the header the client sent. */
export function sniffImage(b: Buffer): ImageType | null {
  if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return { mime: 'image/jpeg', ext: 'jpg' };
  if (b.length >= 8 && b.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return { mime: 'image/png', ext: 'png' };
  if (b.length >= 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') return { mime: 'image/webp', ext: 'webp' };
  return null;
}

/** Width and height read from the file header (no image library on the server). */
export function imageSize(b: Buffer, mime: ImageType['mime']): { width: number; height: number } | null {
  try {
    if (mime === 'image/png') return { width: b.readUInt32BE(16), height: b.readUInt32BE(20) };
    if (mime === 'image/webp') {
      const kind = b.toString('ascii', 12, 16);
      if (kind === 'VP8 ') return { width: b.readUInt16LE(26) & 0x3fff, height: b.readUInt16LE(28) & 0x3fff };
      if (kind === 'VP8L') {
        const bits = b.readUInt32LE(21);
        return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
      }
      if (kind === 'VP8X') return { width: 1 + b.readUIntLE(24, 3), height: 1 + b.readUIntLE(27, 3) };
      return null;
    }
    // JPEG: walk the segments to the first start-of-frame marker.
    let i = 2;
    while (i + 9 < b.length) {
      if (b[i] !== 0xff) return null;
      const marker = b[i + 1];
      if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) {
        i += 2;
        continue;
      }
      const len = b.readUInt16BE(i + 2);
      const sof = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
      if (sof) return { width: b.readUInt16BE(i + 7), height: b.readUInt16BE(i + 5) };
      i += 2 + len;
    }
    return null;
  } catch {
    return null;
  }
}

/** Check, store and record one image. Shared by uploads and the Word import. */
export async function createMedia(input: { body: Buffer; filename: string; alt?: string | null; userId: string | null }): Promise<BlogMedia> {
  if (!input.body.length) throw new BadRequestError('Choose an image to upload.', 'NO_FILE');
  if (input.body.length > MEDIA_MAX_BYTES) throw new BadRequestError('An image can be at most 5 MB.', 'FILE_TOO_LARGE');
  const type = sniffImage(input.body);
  if (!type) throw new BadRequestError('Use a JPG, PNG or WebP image.', 'UNSUPPORTED_IMAGE');
  const size = imageSize(input.body, type.mime);
  if (!size || size.width < MIN_SIDE || size.height < MIN_SIDE || size.width > MAX_SIDE || size.height > MAX_SIDE) {
    throw new BadRequestError(`The image must be between ${MIN_SIDE} and ${MAX_SIDE.toLocaleString('en-IN')} pixels on each side.`, 'BAD_IMAGE_SIZE');
  }
  const id = randomUUID();
  const key = `${BLOG_MEDIA_PREFIX}${id}.${type.ext}`;
  await storage.put(key, input.body, type.mime);
  try {
    return await db.blogMedia.create({
      data: {
        id,
        key,
        filename: (input.filename.trim() || `image.${type.ext}`).slice(0, 200),
        mime: type.mime,
        size: input.body.length,
        width: size.width,
        height: size.height,
        alt: input.alt?.trim().slice(0, 200) || null,
        uploadedById: input.userId,
      },
    });
  } catch (err) {
    await storage.remove(key);
    throw err;
  }
}

/** A ten-minute read link, or null where S3 isn't set up (a developer's machine). */
async function linkFor(key: string): Promise<string | null> {
  try {
    return await storage.presign(key);
  } catch {
    return null;
  }
}

/** What the editor's library shows: a link that works for ten minutes. */
export async function presentMedia(m: BlogMedia) {
  return {
    id: m.id,
    filename: m.filename,
    mime: m.mime,
    size: m.size,
    width: m.width,
    height: m.height,
    alt: m.alt,
    path: mediaPath(m.id),
    url: await linkFor(m.key),
    createdAt: m.createdAt,
  };
}

export async function listMedia(input: { page: number; limit: number; q?: string }) {
  const where = input.q ? { OR: [{ filename: { contains: input.q, mode: 'insensitive' as const } }, { alt: { contains: input.q, mode: 'insensitive' as const } }] } : {};
  const [rows, total] = await Promise.all([
    db.blogMedia.findMany({ where, orderBy: { createdAt: 'desc' }, skip: (input.page - 1) * input.limit, take: input.limit }),
    db.blogMedia.count({ where }),
  ]);
  return { items: await Promise.all(rows.map(presentMedia)), total, page: input.page, limit: input.limit, hasMore: (input.page - 1) * input.limit + rows.length < total };
}

export async function updateMediaAlt(id: string, alt: string | null) {
  const m = await db.blogMedia.findUnique({ where: { id } });
  if (!m) throw new NotFoundError('Image not found.');
  return presentMedia(await db.blogMedia.update({ where: { id }, data: { alt: alt?.trim() || null } }));
}

/** The post using an image, archived ones included: restoring one must not find it gone. */
export async function postUsingMedia(id: string) {
  return db.blogPost.findFirst({
    where: { OR: [{ coverMediaId: id }, { bodyMd: { contains: mediaPath(id) } }] },
    select: { id: true, title: true },
  });
}

export async function deleteMedia(id: string) {
  const m = await db.blogMedia.findUnique({ where: { id } });
  if (!m) throw new NotFoundError('Image not found.');
  const used = await postUsingMedia(id);
  if (used) throw new ConflictError(`This image is used in "${used.title}". Remove it from that post first.`, 'MEDIA_IN_USE');
  await db.blogMedia.delete({ where: { id } });
  await storage.remove(m.key);
  return { ok: true };
}

/** Remove images that were stored but never used (a Word import whose draft failed). */
export async function discardMedia(ids: string[]) {
  for (const id of ids) {
    const m = await db.blogMedia.findUnique({ where: { id } });
    if (!m || (await postUsingMedia(id))) continue;
    await db.blogMedia.delete({ where: { id } });
    await storage.remove(m.key);
  }
}

/** Ten-minute links for a set of library images, by id (the editor's preview). */
export async function mediaUrls(ids: string[]): Promise<Record<string, string>> {
  if (!ids.length) return {};
  const rows = await db.blogMedia.findMany({ where: { id: { in: ids } }, select: { id: true, key: true } });
  const pairs = await Promise.all(rows.map(async (r) => [r.id, await linkFor(r.key)] as const));
  return Object.fromEntries(pairs.filter((p): p is readonly [string, string] => p[1] !== null));
}
