import { randomUUID } from 'node:crypto';
import { Role, type BugAttachment } from '@prisma/client';
import { prismaUnscoped as db } from '../../lib/prisma';
import { BadRequestError, ForbiddenError, NotFoundError } from '../../lib/errors';
import { BUG_FILES_PREFIX, deleteBugObject, presignBugObject, putBugObject } from '../uploads/uploads.service';
import { imageSize, sniffImage } from '../blog-cms/blog-media.service';
import type { BugActor } from './bug-access';
import { BUG_LIMITS } from './bug-rules';

/**
 * Files on bugs and comments (docs/bug-tracker-plan.md, D6): screenshots,
 * PDFs and text/log files, up to 10 MB each. Private in S3; read through a
 * ten-minute link. A file is uploaded first and attached when the report or
 * comment is sent; one never attached is removed after a day.
 */

/** S3, behind one object so the tests can stand in for it. */
export const storage = { put: putBugObject, presign: presignBugObject, remove: deleteBugObject };

type Sniffed = { kind: 'IMAGE' | 'PDF' | 'TEXT'; mime: string; ext: string; width?: number; height?: number };

/** What a file is, from its bytes: never from the name or the header the browser sent. */
export function sniffFile(b: Buffer, filename: string): Sniffed | null {
  const image = sniffImage(b);
  if (image) {
    const size = imageSize(b, image.mime);
    return { kind: 'IMAGE', mime: image.mime, ext: image.ext, ...(size ?? {}) };
  }
  if (b.length >= 6 && (b.toString('ascii', 0, 6) === 'GIF87a' || b.toString('ascii', 0, 6) === 'GIF89a')) {
    return { kind: 'IMAGE', mime: 'image/gif', ext: 'gif', width: b.readUInt16LE(6), height: b.readUInt16LE(8) };
  }
  if (b.length >= 5 && b.toString('ascii', 0, 5) === '%PDF-') return { kind: 'PDF', mime: 'application/pdf', ext: 'pdf' };
  // Text: a log, a JSON reply, a CSV. Valid UTF-8 with no NUL bytes; stored and
  // served as plain text whatever its name, so a browser never runs it.
  if (!b.includes(0)) {
    try {
      new TextDecoder('utf-8', { fatal: true }).decode(b);
      const ext = /\.(log|txt|json|csv|md|xml|har|yaml|yml)$/i.exec(filename)?.[1].toLowerCase() ?? 'txt';
      return { kind: 'TEXT', mime: 'text/plain; charset=utf-8', ext };
    } catch {
      return null;
    }
  }
  return null;
}

export async function uploadFile(input: { body: Buffer; filename: string }, actor: BugActor): Promise<BugAttachment> {
  if (!input.body.length) throw new BadRequestError('Choose a file to attach.', 'NO_FILE');
  if (input.body.length > BUG_LIMITS.fileBytes) throw new BadRequestError('A file can be at most 10 MB.', 'FILE_TOO_LARGE');
  const filename = (input.filename.trim() || 'file').replace(/[\\/\u0000-\u001f]/g, '_').slice(0, 200);
  const what = sniffFile(input.body, filename);
  if (!what) throw new BadRequestError('Attach an image (JPG, PNG, WebP, GIF), a PDF, or a text or log file. For a video, add its link.', 'UNSUPPORTED_FILE');
  const id = randomUUID();
  const key = `${BUG_FILES_PREFIX}${id}.${what.ext}`;
  await storage.put(key, input.body, what.mime);
  try {
    return await db.bugAttachment.create({
      data: { id, key, filename, mime: what.mime, size: input.body.length, kind: what.kind, width: what.width ?? null, height: what.height ?? null, uploaderId: actor.id },
    });
  } catch (err) {
    await storage.remove(key);
    throw err;
  }
}

export async function presentFile(a: BugAttachment) {
  let url: string | null = null;
  try {
    url = await storage.presign(a.key, { filename: a.filename, inline: a.kind === 'IMAGE' });
  } catch {
    url = null; // no S3 on a developer's machine
  }
  return { id: a.id, filename: a.filename, mime: a.mime, size: a.size, kind: a.kind, width: a.width, height: a.height, uploaderId: a.uploaderId, createdAt: a.createdAt, url };
}
export type PresentedFile = Awaited<ReturnType<typeof presentFile>>;

/**
 * The uploader's own, not-yet-attached files with these ids. Anything else in
 * the list (someone else's, already attached, unknown) is refused, so a file
 * can't be moved from one bug to another by naming its id.
 */
export async function claimable(ids: string[], actor: BugActor): Promise<BugAttachment[]> {
  if (!ids.length) return [];
  const rows = await db.bugAttachment.findMany({ where: { id: { in: ids }, uploaderId: actor.id, bugId: null, commentId: null } });
  if (rows.length !== ids.length) throw new BadRequestError('One of the files could not be attached. Upload it again.', 'FILE_NOT_AVAILABLE');
  return rows;
}

/** Remove a file: its uploader or the super admin. Returns it, for the bug's history. */
export async function removeFile(id: string, actor: BugActor): Promise<BugAttachment> {
  const a = await db.bugAttachment.findUnique({ where: { id } });
  if (!a) throw new NotFoundError('File not found.');
  if (a.uploaderId !== actor.id && actor.role !== Role.SUPER_ADMIN) throw new ForbiddenError('Only the person who attached a file, or the super admin, can remove it.');
  await db.bugAttachment.delete({ where: { id } });
  await storage.remove(a.key);
  return a;
}

/** Files uploaded for a report or comment that was never sent: gone after a day. */
export async function purgeUnattached(olderThanMs = 24 * 3_600_000): Promise<number> {
  const old = await db.bugAttachment.findMany({ where: { bugId: null, commentId: null, createdAt: { lt: new Date(Date.now() - olderThanMs) } }, take: 200 });
  for (const a of old) {
    await db.bugAttachment.delete({ where: { id: a.id } });
    await storage.remove(a.key);
  }
  return old.length;
}
