import { Router } from 'express';
import { z } from 'zod';
import { db } from '../../db/knex';
import { notFound, validationError } from '../../lib/http-errors';
import {
  ALLOWED_MIME,
  KEY_PATTERN,
  MAX_IMAGE_BYTES,
  deleteObject,
  headObject,
  newKey,
  presignPut,
  r2,
} from '../../lib/r2';
import { requireRole } from '../../middleware/auth';
import { validate } from '../../middleware/validate';
import { audit } from './audit';
import { idParam, write } from './helpers';

const editors = requireRole('admin', 'editor');
const mime = z.enum(
  Object.keys(ALLOWED_MIME) as [keyof typeof ALLOWED_MIME, ...(keyof typeof ALLOWED_MIME)[]],
  { message: 'Use a JPEG, PNG or WebP image' },
);

const slugText = z
  .string()
  .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)
  .max(150);
export const presignBody = z.object({
  filename: z.string().trim().min(1).max(200),
  mime,
  size: z.number().int().positive().max(MAX_IMAGE_BYTES, 'Image must be 5 MB or smaller'),
  // Phase 10: name the file after its page; one token for all sizes of one upload
  folder: z.enum(['brands', 'reviewers', 'generics']).optional(),
  slug: slugText.optional(),
  token: z
    .string()
    .regex(/^[a-z0-9]{6,12}$/)
    .optional(),
  width: z.number().int().min(16).max(4000).optional(),
});
const variant = z.object({
  key: z.string().regex(KEY_PATTERN, 'Invalid upload key'),
  width: z.number().int().min(16).max(4000),
  height: z.number().int().min(16).max(8000),
});
export const confirmBody = z.object({
  key: z.string().regex(KEY_PATTERN, 'Invalid upload key'),
  width: z.number().int().min(16).max(4000).optional(),
  height: z.number().int().min(16).max(8000).optional(),
  /** all sizes of this upload (e.g. 200w, 400w, 800w) for srcset */
  variants: z.array(variant).max(4).optional(),
  credit: z.string().trim().min(1, 'Say who owns the image (company or contributor)').max(160),
  photoDate: z
    .string()
    .regex(/^\d{4}-\d{2}-\d{2}$/)
    .optional(),
  permissionNote: z.string().trim().max(300).optional(),
  brandId: z.string().regex(/^\d+$/).optional(),
  side: z.enum(['front', 'back']).default('front'),
});

/** BACKEND.md §6: presign → browser PUTs to R2 → confirm (HeadObject check) → rows. */
export function imagesRouter() {
  const r = Router();

  r.post('/images/presign', editors, validate({ body: presignBody }), async (_req, res) => {
    const b = res.locals.valid!.body as z.infer<typeof presignBody>;
    res.json(
      await presignPut(
        newKey(b.mime, { folder: b.folder, slug: b.slug, token: b.token, width: b.width }),
        b.mime,
        b.size,
      ),
    );
  });

  r.post('/images/confirm', editors, validate({ body: confirmBody }), async (_req, res) => {
    const b = res.locals.valid!.body as z.infer<typeof confirmBody>;
    const head = await headObject(b.key);
    if (!head) throw validationError({ key: ['The upload was not found in storage. Upload again.'] });
    if (!(head.mime in ALLOWED_MIME) || head.size > MAX_IMAGE_BYTES) {
      await deleteObject(b.key).catch(() => undefined);
      throw validationError({
        key: ['The uploaded file is not an allowed image (JPEG, PNG, WebP up to 5 MB).'],
      });
    }
    // every extra size must be in storage too, and be an allowed image
    for (const v of b.variants ?? []) {
      if (v.key === b.key) continue;
      const h = await headObject(v.key);
      if (!h || !(h.mime in ALLOWED_MIME) || h.size > MAX_IMAGE_BYTES)
        throw validationError({ variants: [`Size ${v.width}w was not uploaded correctly. Upload again.`] });
    }
    if (b.brandId && !(await db('brands').where({ id: b.brandId }).first()))
      throw validationError({ brandId: ['Medicine not found'] });
    const { publicUrl } = r2();
    const variants = (b.variants ?? []).map((v) => ({
      url: `${publicUrl}/${v.key}`,
      key: v.key,
      width: v.width,
      height: v.height,
    }));
    const image = await write(async (trx) => {
      const [id] = await trx('images').insert({
        r2_key: b.key,
        url: `${publicUrl}/${b.key}`,
        mime: head.mime,
        size_bytes: head.size,
        width: b.width ?? null,
        height: b.height ?? null,
        variants: variants.length ? JSON.stringify(variants) : null,
        credit: b.credit,
        photo_date: b.photoDate ?? null,
        permission_note: b.permissionNote ?? null,
        status: 'published',
      });
      if (b.brandId) {
        // one image per side: replace the previous one
        const old = await trx('brand_images').where({ brand_id: b.brandId, side: b.side }).select('image_id');
        if (old.length) await trx('brand_images').where({ brand_id: b.brandId, side: b.side }).del();
        await trx('brand_images').insert({ brand_id: b.brandId, image_id: id, side: b.side, sort_order: 0 });
      }
      await audit(
        { adminId: res.locals.admin!.id, action: 'uploaded', entity: 'image', entityId: id, label: b.key },
        trx,
      );
      return {
        id: String(id),
        url: `${publicUrl}/${b.key}`,
        credit: b.credit,
        date: b.photoDate ?? '',
        ...(b.width && b.height ? { width: b.width, height: b.height } : {}),
        srcset: variants.map((v) => ({ url: v.url, width: v.width })),
      };
    });
    res.status(201).json(image);
  });

  r.delete('/images/:id', editors, validate({ params: idParam }), async (_req, res) => {
    const id = res.locals.valid!.params.id as string;
    const img = await db('images').where({ id }).first();
    if (!img) throw notFound('Image not found.');
    if (!String(img.r2_key).startsWith('seed/')) {
      const extra = (typeof img.variants === 'string' ? JSON.parse(img.variants) : (img.variants ?? [])) as {
        key: string;
      }[];
      for (const k of new Set([img.r2_key, ...extra.map((v) => v.key)]))
        await deleteObject(k).catch(() => undefined);
    }
    await write(async (trx) => {
      await trx('images').where({ id }).del(); // brand_images cascades
      await audit(
        {
          adminId: res.locals.admin!.id,
          action: 'deleted',
          entity: 'image',
          entityId: id,
          label: img.r2_key,
        },
        trx,
      );
    });
    res.status(204).end();
  });

  return r;
}
