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

const router = Router();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const UPLOADS_AGENT_RECEIPTS_DIR = getUploadsAgentReceiptsDir();

const receiptUpload = multer({
  storage: multer.diskStorage({
    destination: (_req, _file, cb) => {
      if (!fs.existsSync(UPLOADS_AGENT_RECEIPTS_DIR)) {
        fs.mkdirSync(UPLOADS_AGENT_RECEIPTS_DIR, { recursive: true });
      }
      cb(null, UPLOADS_AGENT_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,
  },
});

const getActiveSubscription = async (userId: string, now = new Date()) => {
  return (prisma as any).agentSubscription.findFirst({
    where: {
      userId,
      status: 'ACTIVE',
      AND: [
        { OR: [{ startDate: null }, { startDate: { lte: now } }] },
        { OR: [{ endDate: null }, { endDate: { gt: now } }] },
      ],
    },
    include: { plan: true },
    orderBy: { createdAt: 'desc' },
  });
};

router.get('/plans', async (_req, res: Response) => {
  try {
    const brokerSettings = await getBrokerDetectionSettings();

    const byWindow = new Map(
      (brokerSettings.listingFrequencyRules || []).map((r: any) => [r.window, r] as const),
    );
    const hourRule = byWindow.get('HOUR');
    const dayRule = byWindow.get('DAY');
    const monthRule = byWindow.get('MONTH');
    const lifetimeRule = byWindow.get('LIFETIME');

    const plans = await (prisma as any).agentPlan.findMany({
      where: { isActive: true },
      orderBy: [{ price: 'asc' }, { name: 'asc' }],
    });

    const freePlan = {
      id: 'FREE',
      name: 'Free',
      price: 0,
      currency: 'AED',
      billingPeriod: 'MONTHLY',
      maxListingsPerMonth: typeof monthRule?.maxCount === 'number' ? monthRule.maxCount : null,
      maxActiveListings: null,
      isActive: true,
      features: [
        hourRule ? `Up to ${hourRule.maxCount} listing(s) per hour` : null,
        dayRule ? `Up to ${dayRule.maxCount} listing(s) per day` : null,
        monthRule ? `Up to ${monthRule.maxCount} listing(s) per month` : null,
        lifetimeRule ? `Up to ${lifetimeRule.maxCount} listing(s) lifetime` : null,
      ].filter(Boolean),
    };

    res.json({ plans: [freePlan, ...(plans || [])] });
  } catch (error: any) {
    console.error('Get agent plans error:', error);
    res.status(500).json({
      error: 'Failed to fetch agent plans',
      ...(process.env.NODE_ENV === 'development' && { message: error.message }),
    });
  }
});

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

    const now = new Date();
    const periodStart = new Date(now.getFullYear(), now.getMonth(), 1);

    // Best-effort: if the latest ACTIVE subscription is past endDate, mark it EXPIRED.
    const latest = await (prisma as any).agentSubscription.findFirst({
      where: { userId },
      orderBy: { createdAt: 'desc' },
      select: { id: true, status: true, endDate: true },
    });

    if (latest?.status === 'ACTIVE' && latest.endDate && latest.endDate <= now) {
      await (prisma as any).agentSubscription.update({
        where: { id: latest.id },
        data: { status: 'EXPIRED' },
      });
    }

    const [sub, usage, agentProfile] = await Promise.all([
      (prisma as any).agentSubscription.findFirst({
        where: { userId },
        include: { plan: true },
        orderBy: { createdAt: 'desc' },
      }),
      (prisma as any).agentUsage.findUnique({
        where: { userId_periodStart: { userId, periodStart } },
      }),
      (prisma as any).agentProfile.findUnique({
        where: { userId },
        select: { companyName: true, contactPhone: true, contactEmail: true, licenseNumber: true },
      }),
    ]);

    res.json({ subscription: sub, usage, agentProfile });
  } catch (error: any) {
    console.error('Get agent subscription error:', error);
    res.status(500).json({
      error: 'Failed to fetch subscription',
      ...(process.env.NODE_ENV === 'development' && { message: error.message }),
    });
  }
});

const subscribeSchema = z.object({
  body: z.object({
    planId: z.string().min(1),
    companyName: z.string().min(2),
    contactPhone: z.string().optional(),
    contactEmail: z.string().email().optional(),
    licenseNumber: z.string().optional(),
  }),
});

// Single-submit: subscribe WITH receipt attached (multipart/form-data)
const subscribeWithReceiptSchema = z.object({
  planId: z.string().min(1),
  companyName: z.string().min(2),
  contactPhone: z.string().optional(),
  contactEmail: z.string().email().optional(),
  licenseNumber: z.string().optional(),
  developerId: z.string().optional(),
});

router.post(
  '/subscribe-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 = subscribeWithReceiptSchema.parse({
        planId: String((req as any).body?.planId || '').trim(),
        companyName: String((req as any).body?.companyName || '').trim(),
        contactPhone: String((req as any).body?.contactPhone || '').trim() || undefined,
        contactEmail: String((req as any).body?.contactEmail || '').trim() || undefined,
        licenseNumber: String((req as any).body?.licenseNumber || '').trim() || undefined,
        developerId: String((req as any).body?.developerId || '').trim() || undefined,
      });

      if (parsed.planId === 'FREE') {
        return res.status(400).json({ error: 'Invalid plan', message: 'Free plan is not purchasable.' });
      }

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

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

      const existingPending = await (prisma as any).agentSubscription.findFirst({
        where: { userId, status: 'PENDING' },
        include: { plan: true },
        orderBy: { createdAt: 'desc' },
      });
      if (existingPending) {
        return res.status(200).json({ message: 'Subscription request already pending', subscription: existingPending });
      }

      const existingActive = await getActiveSubscription(userId);
      if (existingActive) {
        return res.status(400).json({ error: 'Already subscribed', message: 'You already have an active agent subscription.' });
      }

      // Optional: auto-map to a developer on first subscription
      const developerId = parsed.developerId?.trim() || undefined;
      const existingMapping = await (prisma as any).developerAgent.findUnique({ where: { userId } });
      if (!existingMapping && developerId) {
        const dev = await (prisma as any).developer.findUnique({ where: { id: developerId } });
        if (dev) {
          await (prisma as any).developerAgent.create({
            data: {
              developerId: dev.id,
              userId,
              role: 'AGENT',
            },
          });
        }
      }

      await (prisma as any).agentProfile.upsert({
        where: { userId },
        update: {
          companyName: parsed.companyName,
          contactPhone: parsed.contactPhone || null,
          contactEmail: parsed.contactEmail || null,
          licenseNumber: parsed.licenseNumber || null,
        },
        create: {
          userId,
          companyName: parsed.companyName,
          contactPhone: parsed.contactPhone || null,
          contactEmail: parsed.contactEmail || null,
          licenseNumber: parsed.licenseNumber || null,
        },
      });

      const filename = (req as any).file.filename;
      const subscription = await (prisma as any).agentSubscription.create({
        data: {
          userId,
          planId: plan.id,
          status: 'PENDING',
          paymentStatus: 'PENDING',
          paymentId: null,
          receiptUrl: `/uploads/agent-receipts/${filename}`,
          receiptUploadedAt: new Date(),
        },
        include: { plan: true },
      });

      return res.status(201).json({ message: 'Subscription request submitted for review', subscription });
    } catch (error: any) {
      console.error('Agent subscribe with receipt error:', error);
      return res.status(500).json({
        error: 'Failed to subscribe',
        ...(process.env.NODE_ENV === 'development' && { message: error.message }),
      });
    }
  },
);

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

    const { planId, companyName, contactPhone, contactEmail, licenseNumber } = (req as any).body;

    if (planId === 'FREE') {
      return res.status(400).json({ error: 'Invalid plan', message: 'Free plan is not purchasable.' });
    }

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

    const existingPending = await (prisma as any).agentSubscription.findFirst({
      where: { userId, status: 'PENDING' },
      include: { plan: true },
      orderBy: { createdAt: 'desc' },
    });
    if (existingPending) {
      return res.status(200).json({ message: 'Subscription request already pending', subscription: existingPending });
    }

    const existingActive = await getActiveSubscription(userId);
    if (existingActive) {
      return res.status(400).json({ error: 'Already subscribed', message: 'You already have an active agent subscription.' });
    }

    await (prisma as any).agentProfile.upsert({
      where: { userId },
      update: {
        companyName,
        contactPhone: contactPhone || null,
        contactEmail: contactEmail || null,
        licenseNumber: licenseNumber || null,
      },
      create: {
        userId,
        companyName,
        contactPhone: contactPhone || null,
        contactEmail: contactEmail || null,
        licenseNumber: licenseNumber || null,
      },
    });

    const subscription = await (prisma as any).agentSubscription.create({
      data: {
        userId,
        planId: plan.id,
        status: 'PENDING',
        paymentStatus: 'PENDING',
        paymentId: null,
      },
      include: { plan: true },
    });

    res.status(201).json({ message: 'Subscription request created. Please upload your payment receipt.', subscription });
  } catch (error: any) {
    console.error('Agent subscribe error:', error);
    res.status(500).json({ error: 'Failed to subscribe', 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 subscriptionId = String((req as any).body?.subscriptionId || '').trim();
    if (!subscriptionId) {
      return res.status(400).json({ error: 'subscriptionId is required' });
    }
    if (!(req as any).file) {
      return res.status(400).json({ error: 'No file provided' });
    }

    const sub = await (prisma as any).agentSubscription.findUnique({
      where: { id: subscriptionId },
      select: { id: true, userId: true, status: true },
    });

    if (!sub || sub.userId !== userId) {
      return res.status(404).json({ error: 'Subscription not found' });
    }
    if (sub.status !== 'PENDING') {
      return res.status(400).json({ error: 'Receipt upload is only allowed for pending subscriptions' });
    }

    const filename = (req as any).file.filename;
    const updated = await (prisma as any).agentSubscription.update({
      where: { id: subscriptionId },
      data: {
        receiptUrl: `/uploads/agent-receipts/${filename}`,
        receiptUploadedAt: new Date(),
      },
      include: { plan: true },
    });

    res.json({ message: 'Receipt uploaded', subscription: updated });
  } catch (error: any) {
    console.error('Upload agent receipt error:', error);
    res.status(500).json({ error: 'Failed to upload receipt', message: error.message });
  }
});
router.get('/conversion-prompt', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) return res.status(401).json({ error: 'Authentication required' });

    const { shouldShowAgentConversionPrompt } = await import('../utils/agentConversion.js');
    const result = await shouldShowAgentConversionPrompt(userId);
    res.json(result);
  } catch (error: any) {
    console.error('Get agent conversion prompt error:', error);
    res.status(500).json({ error: 'Failed to evaluate conversion prompt', message: error.message });
  }
});

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

    const sub = await (prisma as any).agentSubscription.findFirst({
      where: { userId, status: 'ACTIVE' },
      orderBy: { createdAt: 'desc' },
      select: { id: true },
    });

    if (!sub) {
      return res.status(404).json({ error: 'No active subscription found' });
    }

    const updated = await (prisma as any).agentSubscription.update({
      where: { id: sub.id },
      data: { status: 'CANCELED', endDate: new Date() },
      include: { plan: true },
    });

    res.json({ message: 'Subscription canceled', subscription: updated });
  } catch (error: any) {
    console.error('Cancel subscription error:', error);
    res.status(500).json({ error: 'Failed to cancel subscription', message: error.message });
  }
});

export default router;
