import { FastifyPluginAsync } from 'fastify';
import { db } from '../config/database.js';
import { events } from '../db/schema.js';
import { eq } from 'drizzle-orm';
import fs from 'fs';
import path from 'path';

// Fastify JSON schema for event body
const eventBodyJsonSchema = {
  type: 'object',
  required: ['title', 'date', 'description', 'imageUrl', 'displayOrder'],
  properties: {
    title: { type: 'string', minLength: 1, maxLength: 200 },
    date: { type: 'string', minLength: 1, maxLength: 100 },
    description: { type: 'string', minLength: 1 },
    imageUrl: { type: 'string', minLength: 1 },
    displayOrder: { type: 'integer', minimum: 0 },
    isPublished: { type: 'boolean' },
  },
} as const;

const reorderBodyJsonSchema = {
  type: 'object',
  required: ['orders'],
  properties: {
    orders: {
      type: 'array',
      items: {
        type: 'object',
        required: ['id', 'displayOrder'],
        properties: {
          id: { type: 'string' },
          displayOrder: { type: 'integer', minimum: 0 },
        },
      },
    },
  },
} as const;

const eventsRoute: FastifyPluginAsync = async (fastify) => {
  // PUBLIC: List published events (no auth required)
  fastify.get('/events/public', async () => {
    const all = await db.select().from(events)
      .where(eq(events.isPublished, true))
      .orderBy(events.displayOrder);
    return { events: all };
  });

  // List all events (by displayOrder) - admin only
  fastify.get('/events', { preHandler: [fastify.authenticate] }, async () => {
    const all = await db.select().from(events).orderBy(events.displayOrder);
    return { events: all };
  });

  // Get single event
  fastify.get('/events/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const rows = await db.select().from(events).where(eq(events.id, id)).limit(1);
    if (rows.length === 0) return reply.code(404).send({ error: 'Event not found' });
    return { event: rows[0] };
  });

  // Create event
  fastify.post('/events', { schema: { body: eventBodyJsonSchema }, preHandler: [fastify.authenticate] }, async (request, reply) => {
    const data = request.body as any;
    const [row] = await db.insert(events).values(data).returning();
    return reply.code(201).send({ event: row });
  });

  // Update event
  fastify.put('/events/:id', { schema: { body: eventBodyJsonSchema }, preHandler: [fastify.authenticate] }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const data = request.body as any;
    const [row] = await db.update(events).set({ ...data, updatedAt: new Date() }).where(eq(events.id, id)).returning();
    if (!row) return reply.code(404).send({ error: 'Event not found' });
    return { event: row };
  });

  // Upload event image file (multipart)
  fastify.post('/events/upload', {
    preHandler: [fastify.authenticate],
  }, async (request, reply) => {
    try {
      // Expect a single file field named "file"
      const file = await (request as any).file();
      if (!file) {
        return reply.code(400).send({ error: 'No file uploaded' });
      }

      const mime = file.mimetype as string | undefined;
      if (!mime || !mime.startsWith('image/')) {
        return reply.code(400).send({ error: 'Only image uploads are allowed' });
      }

      // Prepare directories - use persistent volume for Fly.io
      const dataDir = process.env.GIT_WORKSPACE_DIR || path.join(process.cwd(), 'data');
      const uploadDir = path.join(dataDir, 'public', 'images', 'events');
      if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });

      // Read uploaded stream into buffer
      const chunks: Buffer[] = [];
      for await (const chunk of file.file) {
        chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
      }
      const inputBuffer = Buffer.concat(chunks);

      // Generate filename
      const stamp = Date.now().toString(36);
      const rand = Math.random().toString(36).slice(2, 8);
      const baseName = `${stamp}-${rand}`;

      // Try to convert to webp and limit size; fallback to original
      let outBuffer: Buffer | null = null;
      let outExt = '.webp';
      try {
        // Lazy load sharp only when needed
        const sharp = (await import('sharp')).default;
        outBuffer = await sharp(inputBuffer)
          .rotate()
          .resize({ width: 1600, withoutEnlargement: true })
          .webp({ quality: 82 })
          .toBuffer();
      } catch (err) {
        fastify.log.warn({ err }, 'Sharp processing failed, using original image');
        outBuffer = inputBuffer;
        // naive extension from mimetype
        const extFromMime = mime.split('/')[1] || 'bin';
        outExt = '.' + extFromMime.replace(/[^a-z0-9]/gi, '').toLowerCase();
      }

      const filename = baseName + outExt;
      const destPath = path.join(uploadDir, filename);
      fs.writeFileSync(destPath, outBuffer);

      // Public URL (served via /static)
      const publicUrl = `/images/events/${filename}`;

      return reply.code(201).send({ imageUrl: publicUrl });

    } catch (err) {
      fastify.log.error({ err }, 'Upload failed');
      return reply.code(500).send({ error: 'Failed to upload image' });
    }
  });

  // Delete event
  fastify.delete('/events/:id', { preHandler: [fastify.authenticate] }, async (request, reply) => {
    const { id } = request.params as { id: string };
    const [row] = await db.delete(events).where(eq(events.id, id)).returning();
    if (!row) return reply.code(404).send({ error: 'Event not found' });
    return { message: 'Event deleted successfully' };
  });

  // Reorder events (synchronous transaction for better-sqlite3)
  fastify.put('/events/reorder', { schema: { body: reorderBodyJsonSchema }, preHandler: [fastify.authenticate] }, async (request) => {
    const { orders } = request.body as { orders: Array<{ id: string; displayOrder: number }> };
    db.transaction((tx: any) => {
      for (const { id, displayOrder } of orders) {
        tx.update(events).set({ displayOrder }).where(eq(events.id, id)).run?.();
      }
    });
    return { message: 'Events reordered successfully' };
  });
};

export default eventsRoute;
