import type { HttpContext } from '@adonisjs/core/http'

import { uploadBlogImage, readBlogImage } from '#services/blog_uploads'

/**
 * BlogUploadsController — gère les images du blog.
 *
 * - POST /api/v1/admin/uploads (auth + admin)
 *     multipart 'file' → upload MinIO → renvoie { url, contentType, sizeBytes }
 * - GET  /api/v1/uploads/blog/:filename (public)
 *     stream depuis MinIO avec Cache-Control immutable.
 */
export default class BlogUploadsController {
  /**
   * POST /api/v1/admin/uploads — admin only.
   */
  async store({ request, response }: HttpContext) {
    const file = request.file('file', {
      size: '4mb',
      extnames: ['jpg', 'jpeg', 'png', 'webp'],
    })

    if (!file) {
      return response.status(422).json({
        errors: [{ field: 'file', message: 'Fichier manquant (champ multipart `file`).' }],
      })
    }
    if (!file.isValid) {
      return response.status(422).json({
        errors: file.errors.map((e) => ({ field: 'file', message: e.message })),
      })
    }

    try {
      const result = await uploadBlogImage(file)
      return response.status(201).json({
        data: {
          url: result.publicPath,
          contentType: result.contentType,
          sizeBytes: result.sizeBytes,
        },
      })
    } catch (err) {
      const msg = err instanceof Error ? err.message : 'upload_failed'
      return response.status(422).json({ errors: [{ field: 'file', message: msg }] })
    }
  }

  /**
   * GET /api/v1/uploads/blog/:filename — public, cache long.
   */
  async show({ params, response }: HttpContext) {
    const filename = String(params.filename ?? '')
    const result = await readBlogImage(filename)
    if (!result) {
      return response.status(404).send('not_found')
    }

    response.header('Content-Type', result.contentType)
    // Filename = uuid → contenu immuable. Cache infini, pas de revalidation.
    response.header('Cache-Control', 'public, max-age=31536000, immutable')
    return response.send(result.buffer)
  }
}
