import { Router, Response } from 'express';
import prisma from '../lib/prisma.js';
import { z } from 'zod';
import { authenticateToken, AuthRequest } from '../middleware/auth.middleware.js';
import multer from 'multer';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { getUploadsBoostReceiptsDir } from '../config/uploads.js';

const router = Router();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const UPLOADS_BOOST_RECEIPTS_DIR = getUploadsBoostReceiptsDir();

const receiptUpload = multer({
  storage: multer.diskStorage({
    destination: (_req, _file, cb) => {
      if (!fs.existsSync(UPLOADS_BOOST_RECEIPTS_DIR)) {
        fs.mkdirSync(UPLOADS_BOOST_RECEIPTS_DIR, { recursive: true });
      }
      cb(null, UPLOADS_BOOST_RECEIPTS_DIR);
    },
    filename: (_req, file, cb) => {
      const safeBase = path
        .basename(file.originalname)
        .replace(/[^a-zA-Z0-9._-]/g, '_')
        .slice(0, 80);
      const ext = path.extname(safeBase);
      const stem = safeBase.replace(ext, '') || 'receipt';
      cb(null, `${stem}_${Date.now()}_${Math.random().toString(16).slice(2)}${ext || ''}`);
    },
  }),
  limits: {
    fileSize: 10 * 1024 * 1024,
  },
});

router.get('/plans', async (_req, res: Response) => {
  try {
    const plans = await (prisma as any).propertyBoostPlan.findMany({
      // No free boost plan: hide any 0-price plans from public listing
      where: { isActive: true, price: { gt: 0 } },
      orderBy: [{ days: 'asc' }, { price: 'asc' }],
    });
    res.json({ plans });
  } catch (error: any) {
    console.error('Get boost plans error:', error);
    res.status(500).json({ error: 'Failed to fetch boost plans', message: error.message });
  }
});

router.get('/my', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) return res.status(401).json({ error: 'Authentication required' });

    const requests = await (prisma as any).propertyBoostRequest.findMany({
      where: { userId },
      include: {
        plan: true,
        property: { select: { id: true, title: true, status: true, featured: true, featuredUntil: true } },
      },
      orderBy: { createdAt: 'desc' },
      take: 100,
    });

    res.json({ requests });
  } catch (error: any) {
    console.error('Get my boost requests error:', error);
    res.status(500).json({ error: 'Failed to fetch boost requests', message: error.message });
  }
});

const createRequestSchema = z.object({
  planId: z.string().min(1),
  propertyId: z.string().min(1),
});

const createRequestWithReceiptSchema = z.object({
  planId: z.string().min(1),
  propertyId: z.string().min(1),
});

// Single-submit: create/complete a pending boost request WITH receipt attached
router.post(
  '/request-with-receipt',
  authenticateToken,
  receiptUpload.single('file'),
  async (req: AuthRequest, res: Response) => {
    try {
      const userId = req.userId;
      if (!userId) return res.status(401).json({ error: 'Authentication required' });

      const parsed = createRequestWithReceiptSchema.parse({
        planId: String((req as any).body?.planId || '').trim(),
        propertyId: String((req as any).body?.propertyId || '').trim(),
      });

      if (!(req as any).file) {
        return res.status(400).json({ error: 'Receipt required', message: 'Please upload a payment receipt.' });
      }

      const property = await prisma.property.findUnique({
        where: { id: parsed.propertyId },
        select: { id: true, ownerId: true, status: true },
      });

      if (!property) {
        return res.status(404).json({ error: 'Property not found' });
      }

      if (property.ownerId !== userId) {
        return res.status(403).json({ error: 'You are not allowed to boost this property' });
      }

      const plan = await (prisma as any).propertyBoostPlan.findUnique({ where: { id: parsed.planId } });
      if (!plan || !plan.isActive) {
        return res.status(400).json({ error: 'Invalid boost plan' });
      }

      // No free boost plan allowed
      const planPrice = typeof plan?.price?.toNumber === 'function' ? plan.price.toNumber() : Number(plan?.price);
      if (!Number.isFinite(planPrice) || planPrice <= 0) {
        return res.status(400).json({
          error: 'Invalid boost plan',
          message: 'Boost plans must have a price greater than 0.',
        });
      }

      const filename = (req as any).file.filename;
      const receiptUrl = `/uploads/boost-receipts/${filename}`;

      const existingPending = await (prisma as any).propertyBoostRequest.findFirst({
        where: { userId, propertyId: parsed.propertyId, status: 'PENDING' },
        include: { plan: true, property: true },
        orderBy: { createdAt: 'desc' },
      });

      if (existingPending) {
        const updated = await (prisma as any).propertyBoostRequest.update({
          where: { id: existingPending.id },
          data: {
            planId: parsed.planId,
            receiptUrl,
            receiptUploadedAt: new Date(),
          },
          include: {
            plan: true,
            property: { select: { id: true, title: true, status: true, featured: true, featuredUntil: true } },
          },
        });

        return res.status(200).json({
          message: 'Boost request updated',
          request: updated,
        });
      }

      const created = await (prisma as any).propertyBoostRequest.create({
        data: {
          userId,
          propertyId: parsed.propertyId,
          planId: parsed.planId,
          status: 'PENDING',
          receiptUrl,
          receiptUploadedAt: new Date(),
        },
        include: {
          plan: true,
          property: { select: { id: true, title: true, status: true, featured: true, featuredUntil: true } },
        },
      });

      return res.status(201).json({
        message: 'Boost request submitted for review',
        request: created,
      });
    } catch (error: any) {
      console.error('Create boost request with receipt error:', error);
      return res.status(500).json({ error: 'Failed to submit boost request', message: error.message });
    }
  },
);

router.post('/request', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) return res.status(401).json({ error: 'Authentication required' });

    const parsed = createRequestSchema.parse(req.body);

    const property = await prisma.property.findUnique({
      where: { id: parsed.propertyId },
      select: { id: true, ownerId: true, status: true },
    });

    if (!property) {
      return res.status(404).json({ error: 'Property not found' });
    }

    if (property.ownerId !== userId) {
      return res.status(403).json({ error: 'You are not allowed to boost this property' });
    }

    const plan = await (prisma as any).propertyBoostPlan.findUnique({ where: { id: parsed.planId } });
    if (!plan || !plan.isActive) {
      return res.status(400).json({ error: 'Invalid boost plan' });
    }

    const existingPending = await (prisma as any).propertyBoostRequest.findFirst({
      where: { userId, propertyId: parsed.propertyId, status: 'PENDING' },
      include: { plan: true, property: true },
      orderBy: { createdAt: 'desc' },
    });

    if (existingPending) {
      return res.status(200).json({ message: 'Boost request already pending', request: existingPending });
    }

    // Legacy endpoint: kept for backward compatibility.
    // New UX should use /request-with-receipt so admins only see complete requests.
    const created = await (prisma as any).propertyBoostRequest.create({
      data: {
        userId,
        propertyId: parsed.propertyId,
        planId: parsed.planId,
        status: 'PENDING',
      },
      include: { plan: true, property: true },
    });

    res.status(201).json({ message: 'Boost request created. Please upload receipt.', request: created });
  } catch (error: any) {
    console.error('Create boost request error:', error);
    res.status(500).json({ error: 'Failed to create boost request', message: error.message });
  }
});

router.post('/upload-receipt', authenticateToken, receiptUpload.single('file'), async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) return res.status(401).json({ error: 'Authentication required' });

    const requestId = String((req as any).body?.requestId || '').trim();
    if (!requestId) {
      return res.status(400).json({ error: 'requestId is required' });
    }
    if (!(req as any).file) {
      return res.status(400).json({ error: 'No file provided' });
    }

    const reqRow = await (prisma as any).propertyBoostRequest.findUnique({
      where: { id: requestId },
      select: { id: true, userId: true, status: true },
    });

    if (!reqRow || reqRow.userId !== userId) {
      return res.status(404).json({ error: 'Boost request not found' });
    }

    if (reqRow.status !== 'PENDING') {
      return res.status(400).json({ error: 'Receipt upload is only allowed for pending requests' });
    }

    const filename = (req as any).file.filename;
    const updated = await (prisma as any).propertyBoostRequest.update({
      where: { id: requestId },
      data: {
        receiptUrl: `/uploads/boost-receipts/${filename}`,
        receiptUploadedAt: new Date(),
      },
      include: {
        plan: true,
        property: { select: { id: true, title: true, status: true, featured: true, featuredUntil: true } },
      },
    });

    res.json({ message: 'Receipt uploaded', request: updated });
  } catch (error: any) {
    console.error('Upload boost receipt error:', error);
    res.status(500).json({ error: 'Failed to upload receipt', message: error.message });
  }
});

export default router;
