import { Router, Request, Response } from 'express';
import { authenticateToken, AuthRequest, requireAdminOrFeatures, userHasAnyFeature } from '../middleware/auth.middleware.js';
import { logActivity, upsertUserDeviceFromRequest } from '../utils/activityLog.js';
import { evaluateListingFrequencyForUser, checkListingFrequencyEnforcement } from '../utils/brokerDetection.js';
import jwt from 'jsonwebtoken';
import { createHash } from 'crypto';
import multer from 'multer';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { getUploadsOwnershipDir, getUploadsValidDir } from '../config/uploads.js';
import { z } from 'zod';
import { PhotoVerificationStatus, RentFrequency, PricingMode } from '@prisma/client';
import { Prisma } from '@prisma/client';
import prisma from '../lib/prisma.js';
import { getPlatformSettings } from '../utils/platformSettings.js';
import { calculatePropertyScoresBatchZScore } from '../utils/propertyScoringZScore.js';

const getUserId = (req: Request) => (req as AuthRequest).userId;

// Helper function to format property response (parse JSON fields)
const formatPropertyResponse = (property: any) => {
  if (!property) return property;
  
  return {
    ...property,
    // Parse JSON fields if they exist
    areaSizes: property.areaSizes ? (typeof property.areaSizes === 'string' ? JSON.parse(property.areaSizes) : property.areaSizes) : null,
    units: property.units ? (typeof property.units === 'string' ? JSON.parse(property.units) : property.units) : null,
    paymentTerms: property.paymentTerms ? (typeof property.paymentTerms === 'string' ? JSON.parse(property.paymentTerms) : property.paymentTerms) : null,
    // Convert Decimal to number for pricePerSqm
    pricePerSqm: property.pricePerSqm ? (typeof property.pricePerSqm === 'object' && property.pricePerSqm.toNumber ? property.pricePerSqm.toNumber() : Number(property.pricePerSqm)) : null,
  };
};

// Simple in-memory throttle for counting views/clicks
const RECENT_WINDOW_MS = 15 * 60 * 1000; // 15 minutes
const recentViews = new Map<string, number>();
const recentClicks = new Map<string, number>();

const shouldCount = (map: Map<string, number>, key: string) => {
  const now = Date.now();
  const last = map.get(key) ?? 0;
  if (now - last < RECENT_WINDOW_MS) return false;
  map.set(key, now);
  return true;
};

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

const UPLOADS_VALID_DIR = getUploadsValidDir();
const UPLOADS_OWNERSHIP_DIR = getUploadsOwnershipDir();

const rawPhotoUpload = multer({
  storage: multer.diskStorage({
    destination: (_req, _file, cb) => {
      if (!fs.existsSync(UPLOADS_VALID_DIR)) {
        fs.mkdirSync(UPLOADS_VALID_DIR, { recursive: true });
      }
      cb(null, UPLOADS_VALID_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, '') || 'photo';
      cb(null, `${stem}_${Date.now()}_${Math.random().toString(16).slice(2)}${ext || ''}`);
    },
  }),
  limits: {
    fileSize: 10 * 1024 * 1024,
  },
});

const ownershipProofUpload = multer({
  storage: multer.diskStorage({
    destination: (_req, _file, cb) => {
      if (!fs.existsSync(UPLOADS_OWNERSHIP_DIR)) {
        fs.mkdirSync(UPLOADS_OWNERSHIP_DIR, { recursive: true });
      }
      cb(null, UPLOADS_OWNERSHIP_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, '') || 'document';
      cb(null, `${stem}_${Date.now()}_${Math.random().toString(16).slice(2)}${ext || ''}`);
    },
  }),
  limits: {
    fileSize: 10 * 1024 * 1024,
  },
});

const safeUnlink = async (filePath: string) => {
  try {
    await fs.promises.unlink(filePath);
  } catch (_e) {
    // best-effort cleanup
  }
};

const cleanupUploadedValidFiles = async (filenames: string[]) => {
  await Promise.all(
    filenames.map(async (name) => {
      const fp = path.join(UPLOADS_VALID_DIR, name);
      await safeUnlink(fp);
    }),
  );
};

const computeFileMd5 = async (filePath: string): Promise<string> => {
  const buffer = await fs.promises.readFile(filePath);
  return createHash('md5').update(buffer).digest('hex');
};

const assertNoDuplicatePhotoHashes = async (args: {
  md5s: string[];
  allowPropertyId?: string;
}) => {
  const unique = new Set<string>();
  for (const md5 of args.md5s) {
    if (unique.has(md5)) {
      throw new Error('DUPLICATE_PHOTO_IN_REQUEST');
    }
    unique.add(md5);
  }

  const existing = await prisma.photoHash.findMany({
    where: { hashType: 'MD5', hashValue: { in: args.md5s } },
    include: { photo: { select: { propertyId: true } } },
    take: 50,
  });

  const disallowed = existing.filter((h) => {
    if (!args.allowPropertyId) return true;
    return h.photo.propertyId !== args.allowPropertyId;
  });

  if (disallowed.length > 0) {
    throw new Error('DUPLICATE_PHOTO_IN_DATABASE');
  }
};

const router = Router();

// Upload raw photo without AI validation (used when platform AI validation is disabled)
router.post('/upload-photo', authenticateToken, rawPhotoUpload.single('file'), async (req: AuthRequest, res: Response) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: 'No file provided' });
    }

    const filePath = path.join(UPLOADS_VALID_DIR, req.file.filename);
    const md5 = await computeFileMd5(filePath);
    try {
      await assertNoDuplicatePhotoHashes({ md5s: [md5] });
    } catch (e: any) {
      if (e?.message === 'DUPLICATE_PHOTO_IN_DATABASE') {
        await safeUnlink(filePath);
        return res.status(400).json({
          error: 'Photo already uploaded',
          message:
            'One or more photos match an image that was uploaded earlier. Please choose different photos and try again.',
        });
      }
      throw e;
    }

    return res.json({
      filename: req.file.filename,
      url: `/uploads/valid/${req.file.filename}`,
      uploaded: true,
    });
  } catch (error: any) {
    console.error('Raw photo upload error:', error);
    res.status(500).json({
      error: 'Failed to upload photo',
      ...(process.env.NODE_ENV === 'development' && { message: error.message }),
    });
  }
});

// Upload validated photo (after AI validation from image detection backend)
// The file has already been validated by the image detection service
router.post('/upload-validated-photo', authenticateToken, rawPhotoUpload.single('file'), async (req: AuthRequest, res: Response) => {
  try {
    if (!req.file) {
      return res.status(400).json({ error: 'No file provided' });
    }

    const filePath = path.join(UPLOADS_VALID_DIR, req.file.filename);
    const md5 = await computeFileMd5(filePath);
    
    // Check for duplicates
    try {
      await assertNoDuplicatePhotoHashes({ md5s: [md5] });
    } catch (e: any) {
      if (e?.message === 'DUPLICATE_PHOTO_IN_DATABASE') {
        await safeUnlink(filePath);
        return res.status(400).json({
          error: 'Photo already uploaded',
          message:
            'One or more photos match an image that was uploaded earlier. Please choose different photos and try again.',
        });
      }
      throw e;
    }

    return res.json({
      filename: req.file.filename,
      url: `/uploads/valid/${req.file.filename}`,
      uploaded: true,
      validated: true, // Indicates this was AI-validated
    });
  } catch (error: any) {
    console.error('Validated photo upload error:', error);
    res.status(500).json({
      error: 'Failed to upload validated photo',
      ...(process.env.NODE_ENV === 'development' && { message: error.message }),
    });
  }
});

// Upload ownership proof document (stored under uploads/ownership-documents)
router.post(
  '/upload-ownership-proof',
  authenticateToken,
  ownershipProofUpload.single('file'),
  async (req: AuthRequest, res: Response) => {
    try {
      if (!req.file) {
        return res.status(400).json({ error: 'No file provided' });
      }

      return res.json({
        filename: req.file.filename,
        url: `/uploads/ownership-documents/${req.file.filename}`,
        uploaded: true,
      });
    } catch (error: any) {
      console.error('Ownership proof upload error:', error);
      res.status(500).json({
        error: 'Failed to upload ownership proof',
        ...(process.env.NODE_ENV === 'development' && { message: error.message }),
      });
    }
  },
);

// Schema for photos coming from frontend after AI validation
const validatedPhotoSchema = z.object({
  filename: z.string().min(1, 'Filename is required'),
  originalName: z.string().optional(),
  fileSize: z.number().int().nonnegative().optional(),
  mimeType: z.string().optional(),
  isPrimary: z.boolean().optional().default(false),
  order: z.number().int().nonnegative(),
  verificationDetails: z.any().optional(),
});

// Contact method for how buyers can reach the seller
const contactMethodEnum = z.enum(['CHAT_ONLY', 'PHONE_AND_CHAT']);

const normalizeName = (s: string) => s.trim().toLowerCase();

const assertCatalogConstraints = async (args: {
  propertyType: string;
  amenities: string[];
  state?: string;
  city: string;
  regionId?: string;
  cityId?: string;
  subCityId?: string;
}) => {
  const [typeRow, enabledAmenities, enabledRegions, enabledCitiesForRegion] = await Promise.all([
    (prisma as any).catalogPropertyType.findUnique({ where: { key: args.propertyType } }),
    (prisma as any).catalogAmenity.findMany({ where: { enabled: true }, select: { name: true } }),
    (prisma as any).catalogRegion.findMany({ where: { enabled: true }, select: { id: true, name: true } }),
    (async () => {
      if (!args.state || !args.state.trim()) return [] as Array<{ name: string }>;
      const region = await (prisma as any).catalogRegion.findFirst({
        where: { enabled: true, name: args.state.trim() },
        select: { id: true },
      });
      if (!region) return [] as Array<{ name: string }>;
      return (prisma as any).catalogCity.findMany({ where: { enabled: true, regionId: region.id }, select: { name: true } });
    })(),
  ]);

  if (!typeRow || !typeRow.enabled) {
    throw new Error('PROPERTY_TYPE_DISABLED');
  }

  // If catalog amenities exist, enforce membership
  if (enabledAmenities.length > 0 && args.amenities.length > 0) {
    const allowed = new Set(enabledAmenities.map((a) => normalizeName(a.name)));
    const bad = args.amenities.filter((a) => !allowed.has(normalizeName(a)));
    if (bad.length > 0) {
      throw new Error('AMENITY_DISABLED');
    }
  }

  // If regions are configured, ensure provided state is enabled
  if (enabledRegions.length > 0) {
    if ((args.regionId && args.regionId.trim()) || (args.cityId && args.cityId.trim()) || (args.subCityId && args.subCityId.trim())) {
      // If an ID is provided, validate it is enabled. Names (state/city) are validated later by mismatch checks.
      if (args.regionId && args.regionId.trim()) {
        const regionRow = await (prisma as any).catalogRegion.findUnique({
          where: { id: args.regionId.trim() },
          select: { id: true, enabled: true },
        });
        if (!regionRow || !regionRow.enabled) throw new Error('REGION_DISABLED');
      }

      if (args.cityId && args.cityId.trim()) {
        const cityRow = await (prisma as any).catalogCity.findUnique({
          where: { id: args.cityId.trim() },
          select: { id: true, enabled: true, regionId: true },
        });
        if (!cityRow || !cityRow.enabled) throw new Error('CITY_DISABLED');
        if (args.regionId && args.regionId.trim() && String(cityRow.regionId) !== args.regionId.trim()) {
          throw new Error('CITY_REGION_MISMATCH');
        }
      }
    } else {
      // Legacy path: validate by names
      if (!args.state || !args.state.trim()) {
        throw new Error('REGION_REQUIRED');
      }
      const regionOk = enabledRegions.some((r) => normalizeName(r.name) === normalizeName(args.state || ''));
      if (!regionOk) {
        throw new Error('REGION_DISABLED');
      }

      // If cities are configured for that region, enforce membership
      if (enabledCitiesForRegion.length > 0) {
        const ok = enabledCitiesForRegion.some((c) => normalizeName(c.name) === normalizeName(args.city));
        if (!ok) {
          throw new Error('CITY_DISABLED');
        }
      }
    }
  }

  if (args.subCityId && args.subCityId.trim()) {
    const row = await (prisma as any).catalogSubCity.findUnique({
      where: { id: args.subCityId.trim() },
      select: {
        id: true,
        enabled: true,
        name: true,
        city: {
          select: {
            id: true,
            name: true,
            region: { select: { name: true } },
          },
        },
      },
    });

    if (!row || !row.enabled) {
      throw new Error('SUBCITY_DISABLED');
    }

    if (args.cityId && args.cityId.trim() && row.city?.id && String(row.city.id) !== args.cityId.trim()) {
      throw new Error('SUBCITY_CITY_MISMATCH');
    }

    if (row.city?.name && args.city && args.city.trim() && normalizeName(row.city.name) !== normalizeName(args.city)) {
      throw new Error('SUBCITY_CITY_MISMATCH');
    }

    if (args.state && args.state.trim() && row.city?.region?.name) {
      if (normalizeName(row.city.region.name) !== normalizeName(args.state)) {
        throw new Error('SUBCITY_REGION_MISMATCH');
      }
    }
  }
};

// Property creation schema (JSON body, no raw file upload)
const createPropertySchemaBase = z.object({
  title: z.string().min(10, 'Title must be at least 10 characters').max(200, 'Title is too long'),
  description: z.string().max(5000, 'Description is too long').optional(),
  propertyType: z.string().min(1).max(50).refine(async (val) => {
    // Validate that property type exists in catalog and is enabled
    const catalogType = await (prisma as any).catalogPropertyType.findUnique({
      where: { key: val },
      select: { enabled: true },
    });
    return catalogType !== null && catalogType.enabled === true;
  }, {
    message: 'Invalid or disabled property type. Please select a valid property type.',
  }),
  listingType: z.enum(['SALE', 'RENT']).optional().default('SALE'),
  // serviceType is no longer user-selectable; we always create SELF_SERVICE listings.
  serviceType: z.enum(['SELF_SERVICE', 'COOL_SERVICE']).optional().default('SELF_SERVICE'),
  contactMethod: contactMethodEnum.optional().default('CHAT_ONLY'),
  bedrooms: z.number().int().min(0).optional().nullable(),
  bathrooms: z.number().int().min(0).optional().nullable(),
  areaSqft: z.number().int().min(1, 'Area is required'),
  furnishing: z.enum(['FURNISHED', 'UNFURNISHED', 'PARTIALLY_FURNISHED']).optional(),
  address: z.string().min(5, 'Address must be at least 5 characters').max(500, 'Address is too long'),
  city: z.string().min(2, 'City is required').max(100, 'City name is too long'),
  cityId: z.string().optional(),
  subCity: z.string().optional(),
  subCityId: z.string().optional(),
  state: z.string().optional(),
  regionId: z.string().optional(),
  country: z.string().default('Ethiopia'),
  latitude: z.number().finite().optional(),
  longitude: z.number().finite().optional(),
  price: z.string().refine((val) => !isNaN(Number(val)) && Number(val) > 0, {
    message: 'Price must be a valid number',
  }),
  currency: z.string().default('Birr'),
  rentFrequency: z.enum(['MONTHLY', 'YEARLY']).optional(),
  ownershipProofUrl: z.string().min(1).optional(),
  // Photos must have been uploaded and validated by AI prior to submission
  photos: z.array(validatedPhotoSchema).min(3, 'At least 3 photos are required'),
  amenities: z.array(z.string()).optional().default([]),
  // NEW: Pricing mode (simplified - single price field for both modes)
  pricingMode: z.enum(['TOTAL_PRICE', 'PRICE_PER_SQM', 'BOTH']).optional().default('TOTAL_PRICE'),
  // pricePerSqm removed - use price field for both modes
  // NEW: Multiple area sizes (comma-separated string or array)
  areaSizes: z.union([z.string(), z.array(z.number())]).optional(),
  // NEW: Floor information
  floor: z.string().max(255).optional(),
  // NEW: G+ notation for buildings
  gPlus: z.string().max(50).optional(),
  // NEW: Basement levels
  basement: z.number().int().min(0).max(10).optional().nullable(),
  // NEW: Negotiable flag
  isNegotiable: z.boolean().optional().default(false),
  // NEW: Construction status
  isUnderConstruction: z.boolean().optional().default(false),
  // NEW: Land area fields
  totalLandArea: z.number().int().min(1).optional().nullable(),
  builtArea: z.number().int().min(1).optional().nullable(),
  // NEW: Multiple units support
  hasMultipleUnits: z.boolean().optional().default(false),
  units: z.array(z.object({
    floor: z.string().optional(),
    gPlus: z.string().max(50).optional(),
    size: z.number().int().min(1).optional(),
    totalLandArea: z.number().int().min(1).optional().nullable(),
    builtArea: z.number().int().min(1).optional().nullable(),
    bedrooms: z.number().int().min(0).optional().nullable(),
    bathrooms: z.number().int().min(0).optional().nullable(),
    price: z.number().optional(),
    pricePerSqm: z.number().optional(),
  })).optional(),
  // NEW: Payment terms
  downpaymentPercent: z.number().int().min(0).max(100).optional(),
  paymentTermsNotes: z.string().max(1000).optional(),
});

const createPropertySchema = createPropertySchemaBase.superRefine((data, ctx) => {
  if (data.listingType === 'RENT') {
    if (!data.rentFrequency) {
      ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['rentFrequency'], message: 'Rent frequency is required' });
    }
  }
  
  // Note: Property type validation (catalog check) is done via z.string().refine() above
  // Property type-specific field requirements are validated in route handler via validatePropertyTypeRequirements()
  
  // Mutually exclusive: G+ and floor cannot both be set
  if (data.gPlus && data.floor) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ['gPlus'],
      message: 'G+ notation and floor cannot both be set. Building types use G+, apartments/offices use floor.',
    });
  }
  
  // If hasMultipleUnits is true, units array is required
  if (data.hasMultipleUnits && (!data.units || data.units.length === 0)) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ['units'],
      message: 'At least one unit is required when multiple units is enabled',
    });
  }
});

// Helper function to validate property type requirements
const validatePropertyTypeRequirements = async (propertyType: string, data: any): Promise<string[]> => {
  const errors: string[] = [];
  
  const propertyTypeSettings = await (prisma as any).catalogPropertyType.findUnique({
    where: { key: propertyType },
  });

  if (!propertyTypeSettings) {
    errors.push('Invalid property type');
    return errors;
  }

  const hasMultipleUnits = data?.hasMultipleUnits === true;
  const units: any[] = Array.isArray(data?.units) ? data.units : [];

  // Validate required fields based on property type settings
  if (propertyTypeSettings.needsBedrooms) {
    if (data.bedrooms === undefined || data.bedrooms === null) {
      errors.push('Bedrooms are required for this property type');
    }
    if (hasMultipleUnits) {
      const ok = units.length > 0 && units.every((u) => u && u.bedrooms !== undefined && u.bedrooms !== null);
      if (!ok) {
        errors.push('Bedrooms are required for this property type (set bedrooms for each unit)');
      }
    }
  }

  if (propertyTypeSettings.needsBathrooms) {
    if (data.bathrooms === undefined || data.bathrooms === null) {
      errors.push('Bathrooms are required for this property type');
    }
    if (hasMultipleUnits) {
      const ok = units.length > 0 && units.every((u) => u && u.bathrooms !== undefined && u.bathrooms !== null);
      if (!ok) {
        errors.push('Bathrooms are required for this property type (set bathrooms for each unit)');
      }
    }
  }

  if (propertyTypeSettings.needsFloor) {
    if (!data.floor || data.floor.trim() === '') {
      errors.push('Floor is required for this property type');
    }
    if (hasMultipleUnits) {
      const ok =
        units.length > 0 &&
        units.every((u) => typeof u?.floor === 'string' && u.floor.trim() !== '');
      if (!ok) {
        errors.push('Floor is required for this property type (set floor for each unit)');
      }
    }
  }

  if (propertyTypeSettings.usesGPlus) {
    if (!data.gPlus || data.gPlus.trim() === '') {
      errors.push('G+ notation is required for this property type');
    }
    if (hasMultipleUnits) {
      const ok =
        units.length > 0 &&
        units.every((u) => typeof u?.gPlus === 'string' && u.gPlus.trim() !== '');
      if (!ok) {
        errors.push('G+ notation is required for this property type (set G+ for each unit)');
      }
    }
  }

  if (propertyTypeSettings.needsLandArea) {
    if (data.totalLandArea === undefined || data.totalLandArea === null) {
      errors.push('Total land area is required for this property type');
    }
    if (data.builtArea === undefined || data.builtArea === null) {
      errors.push('Built area is required for this property type');
    }
    if (hasMultipleUnits) {
      const ok =
        units.length > 0 &&
        units.every(
          (u) =>
            u &&
            u.totalLandArea !== undefined &&
            u.totalLandArea !== null &&
            u.builtArea !== undefined &&
            u.builtArea !== null,
        );
      if (!ok) {
        errors.push('Land area is required for this property type (set total land area and built area for each unit)');
      }
    }
  }

  // Mutually exclusive: G+ and floor cannot both be set
  if (data.gPlus && data.floor) {
    errors.push('G+ notation and floor cannot both be set. Building types use G+, apartments/offices use floor.');
  }

  return errors;
};

// Create property endpoint (expects JSON with validated photo metadata)
router.post('/', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) {
      return res.status(401).json({ error: 'User not authenticated' });
    }

    const userRow = await prisma.user.findUnique({ where: { id: userId }, select: { role: true } });
    if (userRow?.role === 'BUYER') {
      await prisma.user.update({ where: { id: userId }, data: { role: 'OWNER' } });
    }

    const now = new Date();

    // Agent enforcement: require active subscription and enforce plan limits
    if (userRow?.role === 'AGENT') {
      const latestSub = await (prisma as any).agentSubscription.findFirst({
        where: { userId },
        include: { plan: true },
        orderBy: { createdAt: 'desc' },
      });

      // If latest sub is ACTIVE but expired, block posting (expiry job should also flip status).
      if (latestSub?.status === 'ACTIVE' && latestSub?.endDate && latestSub.endDate <= now) {
        return res.status(403).json({
          error: 'Agent subscription expired',
          code: 'AGENT_SUBSCRIPTION_EXPIRED',
          message: 'Your agent subscription has expired. Please renew your plan to post new listings.',
        });
      }

      if (!latestSub?.plan) {
        const reason = latestSub?.status === 'PENDING'
          ? 'Your subscription request is pending admin approval.'
          : 'Your agent subscription is inactive. Please subscribe and get admin approval to post listings as an agent.';
        return res.status(403).json({
          error: 'Agent subscription required',
          code: 'AGENT_SUBSCRIPTION_REQUIRED',
          message: reason,
        });
      }

      if (latestSub.status !== 'ACTIVE') {
        const reason = latestSub.status === 'PENDING'
          ? 'Your subscription request is pending admin approval.'
          : latestSub.status === 'REJECTED'
            ? 'Your subscription request was rejected. Please contact support or submit a new request.'
            : latestSub.status === 'CANCELED'
              ? 'Your subscription was canceled. Please subscribe again to post as an agent.'
              : latestSub.status === 'EXPIRED'
                ? 'Your agent subscription has expired. Please renew your plan to post new listings.'
                : 'Your agent subscription is inactive. Please subscribe again.';
        return res.status(403).json({
          error: 'Agent subscription inactive',
          code: 'AGENT_SUBSCRIPTION_INACTIVE',
          message: reason,
        });
      }

      const plan = latestSub.plan as any;

      // Ensure AgentUsage is synced from ground truth before enforcing limits
      const { recalcAgentUsageForCurrentPeriod } = await import('../utils/agentUsage.js');
      await recalcAgentUsageForCurrentPeriod(userId, now);

      const periodStart = new Date(now.getFullYear(), now.getMonth(), 1);
      const usage = await (prisma as any).agentUsage.findUnique({
        where: { userId_periodStart: { userId, periodStart } },
      });

      if (typeof plan.maxActiveListings === 'number') {
        if ((usage?.activeListingsCount ?? 0) >= plan.maxActiveListings) {
          return res.status(403).json({
            error: 'Agent listing limit reached',
            code: 'AGENT_ACTIVE_LISTINGS_LIMIT',
            message: `Your plan allows a maximum of ${plan.maxActiveListings} active listings.`,
          });
        }
      }

      if (typeof plan.maxListingsPerMonth === 'number') {
        if ((usage?.listingsPostedCount ?? 0) >= plan.maxListingsPerMonth) {
          return res.status(403).json({
            error: 'Monthly posting limit reached',
            code: 'AGENT_MONTHLY_POSTING_LIMIT',
            message: `Your plan allows ${plan.maxListingsPerMonth} listings per month.`,
          });
        }
      }
    }

    // For non-agent users, optionally enforce broker-detection listing limits
    const enforcement = await checkListingFrequencyEnforcement(userId);
    if (enforcement.blocked) {
      return res.status(429).json({
        error: 'Listing frequency limit exceeded',
        code: 'BROKER_LISTING_LIMIT',
        message:
          enforcement.reason ||
          'You have reached the limit for how many properties you can post in this period. Please try again later or contact support.',
      });
    }

    // Parse and validate body with Zod (using parseAsync because propertyType validation is async)
    const parsed = await createPropertySchema.parseAsync(req.body);

    const {
      title,
      description,
      propertyType,
      listingType,
      contactMethod,
      bedrooms,
      bathrooms,
      areaSqft,
      furnishing,
      address,
      city,
      cityId,
      subCity,
      subCityId,
      state,
      regionId,
      country,
      latitude,
      longitude,
      price,
      currency,
      rentFrequency,
      ownershipProofUrl,
      photos,
      amenities,
      pricingMode,
      areaSizes,
      floor,
      gPlus,
      basement,
      isNegotiable,
      isUnderConstruction,
      totalLandArea,
      builtArea,
      hasMultipleUnits,
      units,
      downpaymentPercent,
      paymentTermsNotes,
    } = parsed;

    // Get property type settings from catalog (already validated in Zod schema)
    const propertyTypeSettings = await (prisma as any).catalogPropertyType.findUnique({
      where: { key: propertyType },
    });

    if (!propertyTypeSettings) {
      return res.status(400).json({
        error: 'Invalid property type',
        message: 'The selected property type does not exist or is disabled.',
      });
    }

    // Determine if bedrooms/bathrooms are needed based on property type settings
    const needsBedrooms = propertyTypeSettings.needsBedrooms ?? false;
    const needsBathrooms = propertyTypeSettings.needsBathrooms ?? false;
    const needsFloor = propertyTypeSettings.needsFloor ?? false;
    const usesGPlus = propertyTypeSettings.usesGPlus ?? false;

    await assertCatalogConstraints({
      propertyType,
      amenities: Array.isArray(amenities) ? amenities : [],
      state: state || undefined,
      city,
      regionId: regionId || undefined,
      cityId: cityId || undefined,
      subCityId: subCityId || undefined,
    });

    let resolvedSubCityName: string | null = subCity ? String(subCity) : null;
    let resolvedSubCityId: string | null = subCityId ? String(subCityId) : null;

    let resolvedCityId: string | null = cityId ? String(cityId) : null;
    let resolvedRegionId: string | null = regionId ? String(regionId) : null;

    // Resolve missing region/city IDs from provided names (phased migration)
    if (!resolvedCityId && city && city.trim()) {
      const row = await (prisma as any).catalogCity.findFirst({
        where: {
          enabled: true,
          name: city.trim(),
          ...(state && state.trim() ? { region: { name: state.trim() } } : {}),
        },
        select: { id: true, regionId: true },
      });
      if (row?.id) {
        resolvedCityId = String(row.id);
        if (!resolvedRegionId && row.regionId) resolvedRegionId = String(row.regionId);
      }
    }

    if (!resolvedRegionId && state && state.trim()) {
      const row = await (prisma as any).catalogRegion.findFirst({
        where: { enabled: true, name: state.trim() },
        select: { id: true },
      });
      if (row?.id) resolvedRegionId = String(row.id);
    }

    // Fallback: if we have a subCity name but not an ID, try to resolve it from the catalog
    if (!resolvedSubCityId && subCity && subCity.trim()) {
      const row = await (prisma as any).catalogSubCity.findFirst({
        where: {
          enabled: true,
          name: subCity.trim(),
          ...(resolvedCityId ? { cityId: resolvedCityId } : {}),
        },
        select: {
          id: true,
          name: true,
          city: { select: { regionId: true } },
        },
      });
      if (row?.id) {
        resolvedSubCityId = String(row.id);
        resolvedSubCityName = row.name;
        if (!resolvedRegionId && row.city?.regionId) {
          resolvedRegionId = String(row.city.regionId);
        }
      }
    }

    if (resolvedSubCityId) {
      const row = await (prisma as any).catalogSubCity.findUnique({
        where: { id: resolvedSubCityId },
        select: { id: true, name: true },
      });
      if (row?.name) {
        resolvedSubCityName = row.name;
      }
    }

    // Ensure uploads/valid exists
    if (!fs.existsSync(UPLOADS_VALID_DIR)) {
      return res.status(500).json({
        error: 'Uploads directory not found',
        message: 'Expected uploads/valid directory to exist. Please verify that the uploads root path is configured correctly.',
      });
    }

    // Verify each referenced file actually exists on disk
    for (const photo of photos) {
      const filePath = path.join(UPLOADS_VALID_DIR, photo.filename);
      if (!fs.existsSync(filePath)) {
        return res.status(400).json({
          error: 'Photo file not found',
          message: `Validated photo file ${photo.filename} does not exist on server. Please re-upload your images.`,
        });
      }
    }

    // Compute hashes once and reject duplicates (DB-backed)
    const photoWithHashes = await Promise.all(
      photos.map(async (photo) => {
        const filePath = path.join(UPLOADS_VALID_DIR, photo.filename);
        const md5 = await computeFileMd5(filePath);
        return { photo, md5 };
      }),
    );

    await assertNoDuplicatePhotoHashes({ md5s: photoWithHashes.map((p) => p.md5) });

    const platformSettings = await getPlatformSettings();
    const verificationStatus = platformSettings.enableAiImageValidation
      ? PhotoVerificationStatus.APPROVED
      : PhotoVerificationStatus.PENDING;

    // Parse areaSizes if provided as string (comma-separated)
    const areaSizesArray = areaSizes
      ? (Array.isArray(areaSizes)
          ? areaSizes
          : typeof areaSizes === 'string'
            ? areaSizes.split(',').map(s => parseFloat(s.trim())).filter(n => !isNaN(n))
            : null)
      : null;

    // Build paymentTerms JSON
    const paymentTerms = (downpaymentPercent !== undefined || paymentTermsNotes)
      ? {
          downpaymentPercent: downpaymentPercent !== undefined ? downpaymentPercent : null,
          notes: paymentTermsNotes || null,
        }
      : null;

    // Create property
    const property = await prisma.property.create({
      data: {
        ownerId: userId,
        title,
        description: description || null,
        propertyType, // Now a String that references CatalogPropertyType.key
        listingType,
        // Always create as SELF_SERVICE – Cool-managed service flow removed from UI
        serviceType: 'SELF_SERVICE',
        contactMethod,
        bedrooms: needsBedrooms ? (bedrooms ?? null) : null,
        bathrooms: needsBathrooms ? (bathrooms ?? null) : null,
        areaSqft,
        furnishing: furnishing || null,
        address,
        city,
        cityId: resolvedCityId,
        subCity: resolvedSubCityName,
        subCityId: resolvedSubCityId,
        state: state || null,
        regionId: resolvedRegionId,
        country: country || 'Ethiopia',
        latitude: typeof latitude === 'number' ? latitude : null,
        longitude: typeof longitude === 'number' ? longitude : null,
        price: parseFloat(price),
        currency: currency || 'Birr',
        rentFrequency: listingType === 'RENT' && rentFrequency ? (rentFrequency as RentFrequency) : null,
        ownershipProofUrl: ownershipProofUrl ? ownershipProofUrl : null,
        // NEW: Pricing mode (simplified - single price field for both modes)
        pricingMode: (pricingMode || 'TOTAL_PRICE') as PricingMode,
        // pricePerSqm removed - use price field for both modes
        // NEW: Multiple area sizes
        areaSizes: areaSizesArray && areaSizesArray.length > 0 ? areaSizesArray : null,
        // NEW: Floor information
        floor: floor || null,
        // NEW: G+ notation for buildings
        gPlus: gPlus || null,
        // NEW: Basement levels
        basement: basement ?? null,
        // NEW: Negotiable flag
        isNegotiable: isNegotiable ?? false,
        // NEW: Construction status
        isUnderConstruction: isUnderConstruction ?? false,
        // NEW: Land area fields
        totalLandArea: totalLandArea ?? null,
        builtArea: builtArea ?? null,
        // NEW: Multiple units support
        hasMultipleUnits: hasMultipleUnits || false,
        units: units && Array.isArray(units) && units.length > 0 ? units : null,
        // NEW: Payment terms
        paymentTerms: paymentTerms ? paymentTerms : null,
        status: 'PENDING', // Start as PENDING, awaiting admin approval
      } as any, // Type assertion needed until Prisma client is regenerated with new fields
    });

    if (userRow?.role === 'AGENT') {
      const now = new Date();
      const periodStart = new Date(now.getFullYear(), now.getMonth(), 1);
      const periodEnd = new Date(now.getFullYear(), now.getMonth() + 1, 1);
      await (prisma as any).agentUsage.upsert({
        where: { userId_periodStart: { userId, periodStart } },
        update: {
          periodEnd,
          listingsPostedCount: { increment: 1 },
        },
        create: {
          userId,
          periodStart,
          periodEnd,
          listingsPostedCount: 1,
          activeListingsCount: 0,
        },
      });
    }

    // Create photo records based on validated metadata
    await Promise.all(
      photoWithHashes.map(async ({ photo, md5 }, index) => {
        const created = await prisma.photo.create({
          data: {
            propertyId: property.id,
            url: `/uploads/valid/${photo.filename}`,
            fileName: photo.originalName || photo.filename,
            fileSize: photo.fileSize ?? null,
            mimeType: photo.mimeType ?? null,
            isPrimary: photo.isPrimary ?? index === 0,
            order: photo.order ?? index,
            verificationStatus,
            verificationDetails: platformSettings.enableAiImageValidation ? (photo.verificationDetails ?? null) : null,
          },
          select: { id: true },
        });

        await prisma.photoHash.upsert({
          where: { photoId_hashType: { photoId: created.id, hashType: 'MD5' } },
          update: { hashValue: md5 },
          create: { photoId: created.id, hashType: 'MD5', hashValue: md5 },
        });
      }),
    );

    // Create amenities if provided
    if (amenities && Array.isArray(amenities) && amenities.length > 0) {
      // Categorize amenities
      const amenityCategories: Record<string, string> = {
        Dishwasher: 'indoor',
        Elevator: 'indoor',
        Balcony: 'outdoor',
        Garden: 'outdoor',
        'Swimming Pool': 'outdoor',
        Parking: 'outdoor',
        Gym: 'community',
        'Near Schools': 'community',
        'Near Shopping': 'community',
      };

      const catalogAmenityRows = await (prisma as any).catalogAmenity.findMany({
        where: { enabled: true, name: { in: amenities.map((a) => String(a)) } },
        select: { name: true, category: true },
      });
      const catalogCategory = new Map<string, string | null>(
        catalogAmenityRows.map((a: any) => [String(a.name), (a.category ?? null) as string | null] as const),
      );

      const amenityPromises = amenities.map((amenityName: string) => {
        const category: string | null =
          catalogCategory.get(String(amenityName)) ?? amenityCategories[String(amenityName)] ?? null;
        return prisma.propertyAmenity.create({
          data: {
            propertyId: property.id,
            name: amenityName,
            category,
          },
        });
      });

      await Promise.all(amenityPromises);
    }

    // Log activity
    const { userDeviceId } = await upsertUserDeviceFromRequest(userId, req);
    await logActivity({
      userId,
      activityType: 'LISTING_CREATED',
      resourceId: property.id,
      resourceType: 'property',
      req,
      userDeviceId,
    });

    const frequencyEvaluation = await evaluateListingFrequencyForUser(userId);

    // Fetch the complete property with relations
    const createdProperty = await prisma.property.findUnique({
      where: { id: property.id },
      include: {
        photos: {
          orderBy: { order: 'asc' },
        },
        amenities: true,
        owner: {
          select: {
            id: true,
            firstName: true,
            lastName: true,
            email: true,
            phone: true,
          },
        },
      },
    });

    // Draft lifecycle: once a listing is successfully created, remove any open draft for this user.
    try {
      await (prisma as any).propertyDraft.deleteMany({ where: { userId } });
    } catch (_e) {
      // best-effort cleanup
    }

    res.status(201).json({
      message: 'Property created successfully',
      property: createdProperty,
      ...(frequencyEvaluation.triggered.length > 0
        ? {
            brokerDetectionWarning: {
              type: 'LISTING_FREQUENCY',
              triggered: frequencyEvaluation.triggered.map((t) => ({
                window: t.rule.window,
                maxCount: t.rule.maxCount,
                listingCount: t.listingCount,
                riskLevel: t.rule.riskLevel,
              })),
            },
          }
        : {}),
    });
  } catch (error: any) {
    console.error('Create property error:', error);

    if (error?.message === 'DUPLICATE_PHOTO_IN_REQUEST') {
      return res.status(400).json({
        error: 'Duplicate photos',
        message: 'The same photo was included multiple times in your upload. Please remove duplicates and try again.',
      });
    }

    if (error?.message === 'DUPLICATE_PHOTO_IN_DATABASE') {
      const bodyPhotos = Array.isArray((req as any)?.body?.photos) ? (req as any).body.photos : [];
      const filenamesToCleanup = Array.isArray(bodyPhotos)
        ? bodyPhotos.map((p: any) => String(p?.filename || '')).filter(Boolean)
        : [];
      if (filenamesToCleanup.length > 0) {
        await cleanupUploadedValidFiles(filenamesToCleanup);
      }
      return res.status(400).json({
        error: 'Photo already uploaded',
        message:
          'One or more photos match an image that was uploaded earlier. Please choose different photos and try again.',
      });
    }

    if (error instanceof z.ZodError) {
      return res.status(400).json({
        error: 'Validation error',
        details: error.errors.map((err) => ({
          path: err.path.join('.'),
          message: err.message,
        })),
      });
    }

    res.status(500).json({
      error: 'Failed to create property',
      message: error.message,
    });
  }
});

// Get user's properties
router.get('/my-properties', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    if (!userId) {
      return res.status(401).json({ error: 'User not authenticated' });
    }

    const properties = await prisma.property.findMany({
      where: { ownerId: userId },
      include: {
        photos: {
          orderBy: { order: 'asc' },
          take: 1, // Just get the primary photo
        },
        _count: {
          select: {
            favorites: true,
            conversations: true,
          },
        },
      },
      orderBy: { createdAt: 'desc' },
    });

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

// Update property (owner only)
const updatePropertySchemaBase = createPropertySchemaBase
  .omit({ serviceType: true }) // service type is fixed at SELF_SERVICE after creation
  .extend({
    photos: createPropertySchemaBase.shape.photos.optional(),
  });

const updatePropertySchema = updatePropertySchemaBase.superRefine((data, ctx) => {
  if (data.listingType === 'RENT') {
    if (!data.rentFrequency) {
      ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['rentFrequency'], message: 'Rent frequency is required' });
    }
  }
  
  // Note: Property type-specific validation is done in the route handler after fetching catalog settings
  
  // If hasMultipleUnits is true, units array is required
  if (data.hasMultipleUnits && (!data.units || data.units.length === 0)) {
    ctx.addIssue({
      code: z.ZodIssueCode.custom,
      path: ['units'],
      message: 'At least one unit is required when multiple units is enabled',
    });
  }
});

router.put('/:id', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    const { id } = req.params;

    if (!userId) {
      return res.status(401).json({ error: 'User not authenticated' });
    }

    // Ensure the property exists and belongs to the user
    const existing = await prisma.property.findUnique({ where: { id } });
    if (!existing) {
      return res.status(404).json({ error: 'Property not found' });
    }
    if (existing.ownerId !== userId) {
      return res.status(403).json({ error: 'You are not allowed to edit this property' });
    }

    const parsed = await updatePropertySchema.parseAsync(req.body);

    // Validate property type requirements if propertyType is being updated
    if (parsed.propertyType) {
      const typeValidationErrors = await validatePropertyTypeRequirements(parsed.propertyType, parsed);
      if (typeValidationErrors.length > 0) {
        return res.status(400).json({
          error: 'Validation error',
          details: typeValidationErrors.map((msg) => ({ message: msg })),
        });
      }
    }

    const {
      title,
      description,
      propertyType,
      listingType,
      contactMethod,
      bedrooms,
      bathrooms,
      areaSqft,
      furnishing,
      address,
      city,
      cityId,
      subCity,
      subCityId,
      state,
      regionId,
      country,
      latitude,
      longitude,
      price,
      currency,
      rentFrequency,
      ownershipProofUrl,
      photos,
      amenities,
      pricingMode,
      areaSizes,
      floor,
      gPlus,
      basement,
      isNegotiable,
      isUnderConstruction,
      totalLandArea,
      builtArea,
      hasMultipleUnits,
      units,
      downpaymentPercent,
      paymentTermsNotes,
    } = parsed;

    // Get property type settings from catalog (already validated in Zod schema)
    const propertyTypeSettings = await (prisma as any).catalogPropertyType.findUnique({
      where: { key: propertyType },
    });

    if (!propertyTypeSettings) {
      return res.status(400).json({
        error: 'Invalid property type',
        message: 'The selected property type does not exist or is disabled.',
      });
    }

    // Determine if bedrooms/bathrooms are needed based on property type settings
    const needsBedrooms = propertyTypeSettings.needsBedrooms ?? false;
    const needsBathrooms = propertyTypeSettings.needsBathrooms ?? false;
    const needsFloor = propertyTypeSettings.needsFloor ?? false;
    const usesGPlus = propertyTypeSettings.usesGPlus ?? false;

    await assertCatalogConstraints({
      propertyType,
      amenities: Array.isArray(amenities) ? amenities : [],
      state: state || undefined,
      city,
      regionId: regionId || undefined,
      cityId: cityId || undefined,
      subCityId: subCityId || undefined,
    });

    let resolvedSubCityName: string | null = subCity ? String(subCity) : null;
    let resolvedSubCityId: string | null = subCityId ? String(subCityId) : null;

    let resolvedCityId: string | null = cityId ? String(cityId) : null;
    let resolvedRegionId: string | null = regionId ? String(regionId) : null;

    // Resolve missing region/city IDs from provided names (phased migration)
    if (!resolvedCityId && city && city.trim()) {
      const row = await (prisma as any).catalogCity.findFirst({
        where: {
          enabled: true,
          name: city.trim(),
          ...(state && state.trim() ? { region: { name: state.trim() } } : {}),
        },
        select: { id: true, regionId: true },
      });
      if (row?.id) {
        resolvedCityId = String(row.id);
        if (!resolvedRegionId && row.regionId) resolvedRegionId = String(row.regionId);
      }
    }

    if (!resolvedRegionId && state && state.trim()) {
      const row = await (prisma as any).catalogRegion.findFirst({
        where: { enabled: true, name: state.trim() },
        select: { id: true },
      });
      if (row?.id) resolvedRegionId = String(row.id);
    }

    // Fallback: if we have a subCity name but not an ID, try to resolve it from the catalog
    if (!resolvedSubCityId && subCity && subCity.trim()) {
      const row = await (prisma as any).catalogSubCity.findFirst({
        where: {
          enabled: true,
          name: subCity.trim(),
          ...(resolvedCityId ? { cityId: resolvedCityId } : {}),
        },
        select: {
          id: true,
          name: true,
          city: { select: { regionId: true } },
        },
      });
      if (row?.id) {
        resolvedSubCityId = String(row.id);
        resolvedSubCityName = row.name;
        if (!resolvedRegionId && row.city?.regionId) {
          resolvedRegionId = String(row.city.regionId);
        }
      }
    }

    if (resolvedSubCityId) {
      const row = await (prisma as any).catalogSubCity.findUnique({
        where: { id: resolvedSubCityId },
        select: { id: true, name: true },
      });
      if (row?.name) {
        resolvedSubCityName = row.name;
      }
    }

    // If photos are provided, validate that files exist + enforce duplicate protection
    let photoWithHashes: Array<{ photo: (typeof parsed)['photos'][number]; md5: string }> | null = null;
    if (photos && photos.length > 0) {
      if (!fs.existsSync(UPLOADS_VALID_DIR)) {
        return res.status(500).json({
          error: 'Uploads directory not found',
          message: 'Expected uploads/valid directory to exist. Please verify that the uploads root path is configured correctly.',
        });
      }

      for (const photo of photos) {
        const filePath = path.join(UPLOADS_VALID_DIR, photo.filename);
        if (!fs.existsSync(filePath)) {
          return res.status(400).json({
            error: 'Photo file not found',
            message: `Validated photo file ${photo.filename} does not exist on server. Please re-upload your images.`,
          });
        }
      }

      photoWithHashes = await Promise.all(
        photos.map(async (photo) => {
          const filePath = path.join(UPLOADS_VALID_DIR, photo.filename);
          const md5 = await computeFileMd5(filePath);
          return { photo, md5 };
        }),
      );

      await assertNoDuplicatePhotoHashes({ md5s: photoWithHashes.map((p) => p.md5), allowPropertyId: id });
    }

    const platformSettings = await getPlatformSettings();
    const verificationStatus = platformSettings.enableAiImageValidation
      ? PhotoVerificationStatus.APPROVED
      : PhotoVerificationStatus.PENDING;

    // Parse areaSizes if provided as string (comma-separated)
    const areaSizesArray = areaSizes
      ? (Array.isArray(areaSizes)
          ? areaSizes
          : typeof areaSizes === 'string'
            ? areaSizes.split(',').map(s => parseFloat(s.trim())).filter(n => !isNaN(n))
            : null)
      : null;

    // Build paymentTerms JSON
    const paymentTerms = (downpaymentPercent !== undefined || paymentTermsNotes)
      ? {
          downpaymentPercent: downpaymentPercent !== undefined ? downpaymentPercent : null,
          notes: paymentTermsNotes || null,
        }
      : null;

    const updatedProperty = await prisma.$transaction(async (tx) => {
      const property = await tx.property.update({
        where: { id },
        data: {
          title,
          description: description || null,
          propertyType, // Now a String that references CatalogPropertyType.key
          listingType,
          contactMethod,
          bedrooms: needsBedrooms ? (bedrooms ?? null) : null,
          bathrooms: needsBathrooms ? (bathrooms ?? null) : null,
          areaSqft,
          furnishing: furnishing || null,
          address,
          city,
          cityId: resolvedCityId,
          subCity: resolvedSubCityName,
          subCityId: resolvedSubCityId,
          state: state || null,
          regionId: resolvedRegionId,
          country: country || 'Ethiopia',
          latitude: typeof latitude === 'number' ? latitude : null,
          longitude: typeof longitude === 'number' ? longitude : null,
          price: parseFloat(price),
          currency: currency || 'Birr',
          rentFrequency: listingType === 'RENT' && rentFrequency ? (rentFrequency as RentFrequency) : null,
          ownershipProofUrl: ownershipProofUrl ? ownershipProofUrl : null,
          // NEW: Pricing mode (simplified - single price field for both modes)
          pricingMode: pricingMode ? (pricingMode as PricingMode) : undefined,
          // pricePerSqm removed - use price field for both modes
          // NEW: Multiple area sizes
          areaSizes: areaSizesArray !== null ? (areaSizesArray && areaSizesArray.length > 0 ? areaSizesArray : null) : undefined,
          // NEW: Floor information
          floor: floor !== undefined ? (floor || null) : undefined,
          // NEW: G+ notation for buildings
          gPlus: gPlus !== undefined ? (gPlus || null) : undefined,
          // NEW: Basement levels
          basement: basement !== undefined ? basement : undefined,
          // NEW: Negotiable flag
          isNegotiable: isNegotiable !== undefined ? isNegotiable : undefined,
          // NEW: Construction status
          isUnderConstruction: isUnderConstruction !== undefined ? isUnderConstruction : undefined,
          // NEW: Land area fields
          totalLandArea: totalLandArea !== undefined ? totalLandArea : undefined,
          builtArea: builtArea !== undefined ? builtArea : undefined,
          // NEW: Multiple units support
          hasMultipleUnits: hasMultipleUnits !== undefined ? hasMultipleUnits : undefined,
          units: units !== undefined ? (units && Array.isArray(units) && units.length > 0 ? units : null) : undefined,
          // NEW: Payment terms
          paymentTerms: paymentTerms !== null ? paymentTerms : undefined,
        } as any, // Type assertion needed until Prisma client is regenerated with new fields
      });

      // If amenities are provided, replace them
      if (amenities && Array.isArray(amenities)) {
        await tx.propertyAmenity.deleteMany({ where: { propertyId: id } });

        const amenityCategories: Record<string, string> = {
          Dishwasher: 'indoor',
          Elevator: 'indoor',
          Balcony: 'outdoor',
          Garden: 'outdoor',
          'Swimming Pool': 'outdoor',
          Parking: 'outdoor',
          Gym: 'community',
          'Near Schools': 'community',
          'Near Shopping': 'community',
        };

        const catalogAmenityRows = await (tx as any).catalogAmenity.findMany({
          where: { enabled: true, name: { in: amenities.map((a) => String(a)) } },
          select: { name: true, category: true },
        });
        const catalogCategory = new Map<string, string | null>(
          catalogAmenityRows.map((a: any) => [String(a.name), (a.category ?? null) as string | null] as const),
        );

        await Promise.all(
          amenities.map((amenityName: string) => {
            const category: string | null =
              catalogCategory.get(String(amenityName)) ?? amenityCategories[String(amenityName)] ?? null;
            return tx.propertyAmenity.create({
              data: {
                propertyId: id,
                name: amenityName,
                category,
              },
            });
          }),
        );
      }

      // If new photos are provided, replace them
      if (photos && photos.length > 0) {
        await tx.photo.deleteMany({ where: { propertyId: id } });

        await Promise.all(
          (photoWithHashes || []).map(async ({ photo, md5 }, index) => {
            const created = await tx.photo.create({
              data: {
                propertyId: id,
                url: `/uploads/valid/${photo.filename}`,
                fileName: photo.originalName || photo.filename,
                fileSize: photo.fileSize ?? null,
                mimeType: photo.mimeType ?? null,
                isPrimary: photo.isPrimary ?? index === 0,
                order: photo.order ?? index,
                verificationStatus,
                verificationDetails: platformSettings.enableAiImageValidation ? (photo.verificationDetails ?? null) : null,
              },
              select: { id: true },
            });

            await tx.photoHash.upsert({
              where: { photoId_hashType: { photoId: created.id, hashType: 'MD5' } },
              update: { hashValue: md5 },
              create: { photoId: created.id, hashType: 'MD5', hashValue: md5 },
            });
          }),
        );
      }

      return property;
    });

    const fullProperty = await prisma.property.findUnique({
      where: { id: updatedProperty.id },
      include: {
        photos: {
          orderBy: { order: 'asc' },
        },
        amenities: true,
        owner: {
          select: {
            id: true,
            firstName: true,
            lastName: true,
            email: true,
            phone: true,
          },
        },
      },
    });

    res.json({
      message: 'Property updated successfully',
      property: fullProperty,
    });
  } catch (error: any) {
    console.error('Update property error:', error);

    if (error?.message === 'DUPLICATE_PHOTO_IN_REQUEST') {
      return res.status(400).json({
        error: 'Duplicate photos',
        message: 'The same photo was included multiple times in your upload. Please remove duplicates and try again.',
      });
    }

    if (error?.message === 'DUPLICATE_PHOTO_IN_DATABASE') {
      const bodyPhotos = Array.isArray((req as any)?.body?.photos) ? (req as any).body.photos : [];
      const filenamesToCleanup = Array.isArray(bodyPhotos)
        ? bodyPhotos.map((p: any) => String(p?.filename || '')).filter(Boolean)
        : [];
      if (filenamesToCleanup.length > 0) {
        await cleanupUploadedValidFiles(filenamesToCleanup);
      }
      return res.status(400).json({
        error: 'Photo already uploaded',
        message:
          'One or more photos match an image that was uploaded earlier. Please choose different photos and try again.',
      });
    }

    if (error instanceof z.ZodError) {
      return res.status(400).json({
        error: 'Validation error',
        details: error.errors.map((err) => ({
          path: err.path.join('.'),
          message: err.message,
        })),
      });
    }

    res.status(500).json({
      error: 'Failed to update property',
      message: error.message,
    });
  }
});

// Update property status (owner or admin)
const updateStatusSchema = z.object({
  status: z.enum(['DRAFT', 'PENDING', 'ACTIVE', 'SOLD', 'ARCHIVED', 'REJECTED']),
});

const getSubAdminGeoFilter = async (userId: string) => {
  const [regionRows, cityRows, subCityRows] = await Promise.all([
    (prisma as any).staffRegionScope.findMany({ where: { userId }, select: { regionId: true } }),
    (prisma as any).staffCityScope.findMany({ where: { userId }, select: { cityId: true } }),
    (prisma as any).staffSubCityScope.findMany({ where: { userId }, select: { subCityId: true } }),
  ]);

  const directRegionIds = (regionRows as any[]).map((r) => String(r.regionId));
  const directCityIds = (cityRows as any[]).map((c) => String(c.cityId));
  const directSubCityIds = (subCityRows as any[]).map((s) => String(s.subCityId));

  const isScoped = directRegionIds.length > 0 || directCityIds.length > 0 || directSubCityIds.length > 0;
  if (!isScoped) return null;

  const mode: 'SUBCITY' | 'CITY' | 'REGION' =
    directSubCityIds.length > 0 ? 'SUBCITY' : directCityIds.length > 0 ? 'CITY' : 'REGION';

  const [citiesForDirectCities, subCitiesForDirectSubCities] = await Promise.all([
    directCityIds.length > 0
      ? (prisma as any).catalogCity.findMany({
          where: { id: { in: directCityIds } },
          select: { id: true, regionId: true },
        })
      : ([] as any[]),
    directSubCityIds.length > 0
      ? (prisma as any).catalogSubCity.findMany({
          where: { id: { in: directSubCityIds } },
          select: { id: true, cityId: true, city: { select: { regionId: true } } },
        })
      : ([] as any[]),
  ]);

  const derivedRegionIds = new Set<string>(directRegionIds);
  for (const row of citiesForDirectCities as any[]) {
    if (row?.regionId) derivedRegionIds.add(String(row.regionId));
  }
  for (const row of subCitiesForDirectSubCities as any[]) {
    if (row?.city?.regionId) derivedRegionIds.add(String(row.city.regionId));
  }

  const derivedCityIds = new Set<string>(directCityIds);
  for (const row of subCitiesForDirectSubCities as any[]) {
    if (row?.cityId) derivedCityIds.add(String(row.cityId));
  }
  if (mode === 'REGION' && derivedRegionIds.size > 0) {
    const cities = await (prisma as any).catalogCity.findMany({
      where: { regionId: { in: Array.from(derivedRegionIds) } },
      select: { id: true },
    });
    for (const c of cities as any[]) {
      if (c?.id) derivedCityIds.add(String(c.id));
    }
  }

  const derivedSubCityIds = new Set<string>(directSubCityIds);
  if (mode !== 'SUBCITY' && derivedCityIds.size > 0) {
    const subs = await (prisma as any).catalogSubCity.findMany({
      where: { cityId: { in: Array.from(derivedCityIds) } },
      select: { id: true },
    });
    for (const s of subs as any[]) {
      if (s?.id) derivedSubCityIds.add(String(s.id));
    }
  }

  const [allowedRegions, allowedCities, allowedSubCities] = await Promise.all([
    derivedRegionIds.size > 0
      ? (prisma as any).catalogRegion.findMany({
          where: { id: { in: Array.from(derivedRegionIds) } },
          select: { id: true, name: true },
        })
      : ([] as any[]),
    derivedCityIds.size > 0
      ? (prisma as any).catalogCity.findMany({
          where: { id: { in: Array.from(derivedCityIds) } },
          select: { id: true, name: true },
        })
      : ([] as any[]),
    derivedSubCityIds.size > 0
      ? (prisma as any).catalogSubCity.findMany({
          where: { id: { in: Array.from(derivedSubCityIds) } },
          select: { id: true, name: true },
        })
      : ([] as any[]),
  ]);

  const allowedRegionIdList = (allowedRegions as any[]).map((r) => String(r.id));
  const allowedRegionNames = (allowedRegions as any[]).map((r) => String(r.name));
  const allowedCityIdList = (allowedCities as any[]).map((c) => String(c.id));
  const allowedCityNames = (allowedCities as any[]).map((c) => String(c.name));
  const allowedSubCityIdList = (allowedSubCities as any[]).map((s) => String(s.id));
  const allowedSubCityNames = (allowedSubCities as any[]).map((s) => String(s.name));

  const or: any[] = [];
  if (mode === 'SUBCITY') {
    if (allowedSubCityIdList.length > 0) or.push({ subCityId: { in: allowedSubCityIdList } });
    if (allowedSubCityNames.length > 0) or.push({ subCityId: null, subCity: { in: allowedSubCityNames } });
  } else if (mode === 'CITY') {
    if (allowedCityIdList.length > 0) or.push({ cityId: { in: allowedCityIdList } });
    if (allowedCityNames.length > 0) or.push({ cityId: null, city: { in: allowedCityNames } });
    if (allowedSubCityIdList.length > 0) or.push({ subCityId: { in: allowedSubCityIdList } });
    if (allowedSubCityNames.length > 0) or.push({ subCityId: null, subCity: { in: allowedSubCityNames } });
  } else {
    if (allowedRegionIdList.length > 0) or.push({ regionId: { in: allowedRegionIdList } });
    if (allowedRegionNames.length > 0) or.push({ regionId: null, state: { in: allowedRegionNames } });
    if (allowedCityIdList.length > 0) or.push({ cityId: { in: allowedCityIdList } });
    if (allowedCityNames.length > 0) or.push({ cityId: null, city: { in: allowedCityNames } });
  }

  if (or.length === 0) return null;
  return { OR: or };
};

router.patch('/:id/status', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    const userRole = req.user?.role;
    const { id } = req.params;

    if (!userId) {
      return res.status(401).json({ error: 'User not authenticated' });
    }

    const isAdmin = userRole === 'ADMIN';
    const isSubAdmin = userRole === 'SUB_ADMIN';
    const subAdminCanReview =
      isSubAdmin && userId ? await userHasAnyFeature(userId, ['PROPERTY_REVIEW']) : false;

    const geoFilter = !isAdmin && subAdminCanReview && userId ? await getSubAdminGeoFilter(userId) : null;

    const existing = await prisma.property.findFirst({
      where: {
        id,
        ...(geoFilter ? geoFilter : {}),
      },
    });
    if (!existing) {
      return res.status(404).json({ error: 'Property not found' });
    }

    // Check permissions: Admin can change any property, Owner can only change their own
    const isOwner = existing.ownerId === userId;

    if (!isAdmin && !subAdminCanReview && !isOwner) {
      return res.status(403).json({ error: 'You are not allowed to update this property' });
    }

    const parsed = updateStatusSchema.parse(req.body);
    const { status } = parsed;

    // Define status transitions based on role
    // Admin can do all transitions (approval workflow)
    const adminTransitions: Record<string, string[]> = {
      DRAFT: ['PENDING', 'ACTIVE', 'ARCHIVED', 'REJECTED'],
      PENDING: ['ACTIVE', 'DRAFT', 'ARCHIVED', 'REJECTED'],
      ACTIVE: ['SOLD', 'ARCHIVED', 'DRAFT', 'PENDING'],
      SOLD: ['ARCHIVED', 'ACTIVE'],
      ARCHIVED: ['DRAFT', 'ACTIVE'],
      REJECTED: ['DRAFT', 'PENDING'],
    };

    // Seller/Owner can only change ACTIVE properties to SOLD or ARCHIVED
    // They can also reactivate ARCHIVED properties back to ACTIVE (if admin previously approved)
    const ownerTransitions: Record<string, string[]> = {
      ACTIVE: ['SOLD', 'ARCHIVED'],
      ARCHIVED: ['ACTIVE'], // Can reactivate if it was previously active
      SOLD: [], // Once sold, cannot change (admin can reactivate if needed)
    };

    // Determine allowed transitions based on role
    const transitions = isAdmin || subAdminCanReview ? adminTransitions : ownerTransitions;
    const allowedStatuses = transitions[existing.status] || [];

    // Sellers cannot change DRAFT, PENDING, or REJECTED statuses
    if (!isAdmin && !subAdminCanReview && ['DRAFT', 'PENDING', 'REJECTED'].includes(existing.status)) {
      return res.status(403).json({
        error: 'Status change not allowed',
        message: 'Only administrators can change the status of draft, pending, or rejected properties. Please wait for admin approval.',
      });
    }

    if (!allowedStatuses.includes(status)) {
      const roleMessage = isAdmin || subAdminCanReview 
        ? `Admin allowed transitions: ${adminTransitions[existing.status]?.join(', ') || 'none'}`
        : `As a seller, you can only change ACTIVE properties to: SOLD or ARCHIVED`;
      
      return res.status(400).json({
        error: 'Invalid status transition',
        message: `Cannot change status from ${existing.status} to ${status}. ${roleMessage}`,
      });
    }

    // Update status
    const updateData: any = { status };
    
    // Set publishedAt when transitioning to ACTIVE (reset reminder)
    if (status === 'ACTIVE') {
      updateData.publishedAt = new Date();
      updateData.autoArchiveReminderSentAt = null;
    }

    const updatedProperty = await prisma.property.update({
      where: { id },
      data: updateData,
      include: {
        photos: {
          orderBy: { order: 'asc' },
          take: 1,
        },
        amenities: {
          take: 5,
        },
      },
    });

    // Log activity
    const { userDeviceId } = await upsertUserDeviceFromRequest(userId, req);
    await logActivity({
      userId,
      activityType: 'LISTING_STATUS_CHANGED',
      resourceId: id,
      resourceType: 'property',
      metadata: {
        statusChange: {
          from: existing.status,
          to: status,
        },
      },
      req,
      userDeviceId,
    });

    res.json({
      message: 'Property status updated successfully',
      property: updatedProperty,
    });
  } catch (error: any) {
    console.error('Update property status error:', error);

    if (error instanceof z.ZodError) {
      return res.status(400).json({
        error: 'Validation error',
        details: error.errors.map((err) => ({
          path: err.path.join('.'),
          message: err.message,
        })),
      });
    }

    res.status(500).json({
      error: 'Failed to update property status',
      message: error.message,
    });
  }
});

// Update property featured flag (admin or subadmin with PROPERTY_REVIEW)
const updateFeaturedSchema = z.object({
  featured: z.boolean(),
});

router.patch('/:id/featured', authenticateToken, async (req: AuthRequest, res: Response) => {
  try {
    const userId = req.userId;
    const userRole = req.user?.role;
    const { id } = req.params;

    if (!userId) {
      return res.status(401).json({ error: 'User not authenticated' });
    }

    const isAdmin = userRole === 'ADMIN';
    const isSubAdmin = userRole === 'SUB_ADMIN';
    const subAdminCanReview =
      isSubAdmin && userId ? await userHasAnyFeature(userId, ['PROPERTY_REVIEW']) : false;

    const geoFilter = !isAdmin && subAdminCanReview && userId ? await getSubAdminGeoFilter(userId) : null;

    const existing = await prisma.property.findFirst({
      where: {
        id,
        ...(geoFilter ? geoFilter : {}),
      },
    });
    if (!existing) {
      return res.status(404).json({ error: 'Property not found' });
    }

    if (!isAdmin && !subAdminCanReview) {
      return res.status(403).json({ error: 'You are not allowed to update featured status' });
    }

    const parsed = updateFeaturedSchema.parse(req.body);
    const { featured } = parsed;

    const updatedProperty = await prisma.property.update({
      where: { id },
      data: {
        featured,
        featuredUntil: featured ? existing.featuredUntil : null,
      },
      include: {
        photos: {
          orderBy: { order: 'asc' },
          take: 1,
        },
      },
    });

    const { userDeviceId } = await upsertUserDeviceFromRequest(userId, req);
    await logActivity({
      userId,
      activityType: 'LISTING_STATUS_CHANGED',
      resourceId: id,
      resourceType: 'property',
      metadata: {
        featuredChange: { from: existing.featured, to: featured },
      },
      req,
      userDeviceId,
    });

    res.json({ message: 'Property featured updated successfully', property: updatedProperty });
  } catch (error: any) {
    console.error('Update property featured error:', error);

    if (error instanceof z.ZodError) {
      return res.status(400).json({
        error: 'Validation error',
        details: error.errors.map((err) => ({
          path: err.path.join('.'),
          message: err.message,
        })),
      });
    }

    res.status(500).json({
      error: 'Failed to update property featured',
      message: error.message,
    });
  }
});

// Deterministic seeded RNG (mulberry32)
const createSeededRng = (seed: string) => {
  let h = 1779033703 ^ seed.length;
  for (let i = 0; i < seed.length; i++) {
    h = Math.imul(h ^ seed.charCodeAt(i), 3432918353);
    h = (h << 13) | (h >>> 19);
  }
  return () => {
    h = Math.imul(h ^ (h >>> 16), 2246822507);
    h = Math.imul(h ^ (h >>> 13), 3266489909);
    const t = (h ^= h >>> 16) >>> 0;
    return t / 4294967296;
  };
};

const shuffleInPlace = <T>(arr: T[], rng: () => number) => {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(rng() * (i + 1));
    [arr[i], arr[j]] = [arr[j], arr[i]];
  }
};

const isFeaturedActive = (property: any, now: Date) => {
  if (!property.featured) return false;
  if (property.featuredUntil && property.featuredUntil <= now) return false;
  return true;
};

const haversineKm = (a: { lat: number; lng: number }, b: { lat: number; lng: number }) => {
  const R = 6371;
  const dLat = ((b.lat - a.lat) * Math.PI) / 180;
  const dLng = ((b.lng - a.lng) * Math.PI) / 180;
  const lat1 = (a.lat * Math.PI) / 180;
  const lat2 = (b.lat * Math.PI) / 180;
  const sin1 = Math.sin(dLat / 2);
  const sin2 = Math.sin(dLng / 2);
  const h = sin1 * sin1 + Math.cos(lat1) * Math.cos(lat2) * (sin2 * sin2);
  return 2 * R * Math.asin(Math.min(1, Math.sqrt(h)));
};

// Get all active properties for homepage with blended ranking
router.get('/', async (req: Request, res: Response) => {
  console.time('properties-fetch');
  console.log('FETCH /api/properties hit', new Date().toISOString(), 'Query:', req.query);
  try {
    const {
      page = '1',
      limit = '12',
      featured = 'false',
      listingType,
      state,
      regionId,
      minPrice,
      maxPrice,
      minBedrooms,
      maxBedrooms,
      minBathrooms,
      maxBathrooms,
      minArea,
      maxArea,
      minGPlus,
      maxGPlus,
      minBasement,
      maxBasement,
      city,
      cityId,
      subCity,
      subCityId,
      propertyType,
      furnishing,
      search,
      amenities,
    } = req.query as Record<string, string | undefined>;

    const pageNum = Math.max(1, parseInt(page as string));
    const limitNum = Math.min(50, Math.max(1, parseInt(limit as string)));
    const isFeaturedOnly = featured === 'true';

    const now = new Date();

    // Filters
    const baseWhere: any = { status: 'ACTIVE' };
    if (listingType === 'SALE' || listingType === 'RENT') {
      baseWhere.listingType = listingType;
    }

    if (city && city.trim()) {
      baseWhere.city = city.trim();
    }

    if (cityId && cityId.trim()) {
      baseWhere.cityId = cityId.trim();
    }

    if (state && state.trim()) {
      baseWhere.state = state.trim();
    }

    if (regionId && regionId.trim()) {
      baseWhere.regionId = regionId.trim();
    }

    if (subCityId && subCityId.trim()) {
      const parts = subCityId
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean);
      if (parts.length === 1) {
        baseWhere.subCityId = parts[0];
      } else if (parts.length > 1) {
        baseWhere.subCityId = { in: parts };
      }
    } else if (subCity && subCity.trim()) {
      // Allow comma-separated list of subCities
      const parts = subCity
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean);
      if (parts.length === 1) {
        baseWhere.subCity = parts[0];
      } else if (parts.length > 1) {
        baseWhere.subCity = { in: parts };
      }
    }

    // Property type is now a String, so we can filter directly
    if (propertyType) {
      baseWhere.propertyType = propertyType;
    }

    if (furnishing && ['FURNISHED', 'UNFURNISHED', 'PARTIALLY_FURNISHED'].includes(furnishing)) {
      baseWhere.furnishing = furnishing;
    }

    if (search && search.trim()) {
      const q = search.trim();
      baseWhere.OR = [
        { title: { contains: q } },
        { description: { contains: q } },
        { address: { contains: q } },
        { city: { contains: q } },
        { subCity: { contains: q } },
      ];
    }

    if (amenities && amenities.trim()) {
      const parts = amenities
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean);
      if (parts.length > 0) {
        baseWhere.amenities = {
          some: {
            name: { in: parts },
          },
        };
      }
    }

    const num = (val?: string) => {
      if (!val) return undefined;
      const parsed = Number(val);
      return Number.isFinite(parsed) ? parsed : undefined;
    };

    const minPriceNum = num(minPrice);
    const maxPriceNum = num(maxPrice);
    if (minPriceNum !== undefined || maxPriceNum !== undefined) {
      baseWhere.price = {
        ...(minPriceNum !== undefined ? { gte: minPriceNum } : {}),
        ...(maxPriceNum !== undefined ? { lte: maxPriceNum } : {}),
      };
    }

    const minBedroomsNum = num(minBedrooms);
    const maxBedroomsNum = num(maxBedrooms);
    if (minBedroomsNum !== undefined || maxBedroomsNum !== undefined) {
      baseWhere.bedrooms = {
        ...(minBedroomsNum !== undefined ? { gte: minBedroomsNum } : {}),
        ...(maxBedroomsNum !== undefined ? { lte: maxBedroomsNum } : {}),
      };
    }

    const minBathroomsNum = num(minBathrooms);
    const maxBathroomsNum = num(maxBathrooms);
    if (minBathroomsNum !== undefined || maxBathroomsNum !== undefined) {
      baseWhere.bathrooms = {
        ...(minBathroomsNum !== undefined ? { gte: minBathroomsNum } : {}),
        ...(maxBathroomsNum !== undefined ? { lte: maxBathroomsNum } : {}),
      };
    }

    const minAreaNum = num(minArea);
    const maxAreaNum = num(maxArea);
    if (minAreaNum !== undefined || maxAreaNum !== undefined) {
      baseWhere.areaSqft = {
        ...(minAreaNum !== undefined ? { gte: minAreaNum } : {}),
        ...(maxAreaNum !== undefined ? { lte: maxAreaNum } : {}),
      };
    }

    // G+ filter will be applied post-processing since gPlus is stored as string "G+5"
    // We'll filter after fetching all properties

    // Basement filter
    const minBasementNum = num(minBasement);
    const maxBasementNum = num(maxBasement);
    if (minBasementNum !== undefined || maxBasementNum !== undefined) {
      baseWhere.basement = {
        ...(minBasementNum !== undefined ? { gte: minBasementNum } : {}),
        ...(maxBasementNum !== undefined ? { lte: maxBasementNum } : {}),
      };
    }

    // Featured-only requests (e.g., admin or dedicated section)
    if (isFeaturedOnly) {
      const featuredWhere = {
        ...baseWhere,
        featured: true,
        OR: [{ featuredUntil: null }, { featuredUntil: { gt: now } }],
      };

      const featuredCandidates = await prisma.property.findMany({
        where: featuredWhere,
        include: {
          photos: {
            orderBy: [
              { isPrimary: 'desc' },
              { order: 'asc' },
            ],
            take: 1,
          },
          amenities: {
            select: {
              id: true,
            },
          },
          owner: {
            select: {
              id: true,
              role: true,
              verified: true,
              agentProfile: {
                select: {
                  companyName: true,
                  verificationStatus: true,
                },
              },
            },
          },
          boostRequests: {
            where: {
              status: 'APPROVED',
            },
            include: {
              plan: {
                select: {
                  days: true,
                },
              },
            },
            take: 1,
          },
        },
        take: Math.min(200, limitNum * 10), // Get more candidates for scoring (max 200 to prevent CPU spike)
      });

      // NEW: Efficient Z-score based scoring for featured properties
      const featuredScoreMap = await calculatePropertyScoresBatchZScore(featuredCandidates, now);

      // Attach scores and sort by score
      const scoredFeatured = featuredCandidates
        .map((p) => ({
          ...p,
          score: featuredScoreMap.get(p.id) || {
            finalScore: 0,
            featuredBoost: 0,
            engagementZScore: 0,
            recencyScore: 0,
            agentBoost: 0,
            qualityScore: 0,
          },
        }))
        .sort((a, b) => {
          const scoreDiff = b.score.finalScore - a.score.finalScore;
          if (scoreDiff !== 0) return scoreDiff;
          const aTime = a.publishedAt?.getTime() || 0;
          const bTime = b.publishedAt?.getTime() || 0;
          return bTime - aTime;
        });

      const total = await prisma.property.count({ where: featuredWhere });
      const start = (pageNum - 1) * limitNum;
      const properties = scoredFeatured
        .slice(start, start + limitNum)
        .map((p) => {
          const { score, ...propertyWithoutScore } = p;
          return propertyWithoutScore;
        });

      return res.json({
        properties,
        pagination: {
          currentPage: pageNum,
          totalPages: Math.ceil(total / limitNum),
          totalItems: total,
          itemsPerPage: limitNum,
        },
      });
    }

    // NEW: Efficient Z-score based ranking system
    // Fetch candidates with reasonable limit for scoring
    const MAX_CANDIDATES = 300;
    const startTime = Date.now();
    
    const candidates = await prisma.property.findMany({
      where: baseWhere,
      include: {
        photos: {
          orderBy: [
            { isPrimary: 'desc' },
            { order: 'asc' },
          ],
          take: 1,
        },
        amenities: {
          select: {
            id: true,
          },
        },
        owner: {
          select: {
            id: true,
            role: true,
            verified: true,
            agentProfile: {
              select: {
                companyName: true,
                verificationStatus: true,
              },
            },
          },
        },
        boostRequests: {
          where: {
            status: 'APPROVED',
          },
          include: {
            plan: {
              select: {
                days: true,
              },
            },
          },
          take: 1,
        },
      },
      orderBy: { publishedAt: 'desc' },
      take: MAX_CANDIDATES, // Limit to prevent CPU spike
    });
    
    const fetchTime = Date.now() - startTime;
    if (fetchTime > 1000) {
      console.warn(`[PERFORMANCE] Property fetch took ${fetchTime}ms, found ${candidates.length} candidates`);
    }

    // Calculate scores using efficient Z-score normalization (O(n) instead of O(n²))
    const scoreStartTime = Date.now();
    const scoreMap = await calculatePropertyScoresBatchZScore(candidates, now);
    const scoreTime = Date.now() - scoreStartTime;
    if (scoreTime > 1000) {
      console.warn(`[PERFORMANCE] Property scoring took ${scoreTime}ms for ${candidates.length} properties`);
    }

    // Attach scores to properties
    let scoredProperties = candidates.map((p) => ({
      ...p,
      score: scoreMap.get(p.id) || {
        finalScore: 0,
        featuredBoost: 0,
        engagementZScore: 0,
        recencyScore: 0,
        agentBoost: 0,
        qualityScore: 0,
      },
    }));

    // Apply G+ filter post-processing (since gPlus is stored as string "G+5")
    const minGPlusNum = num(minGPlus);
    const maxGPlusNum = num(maxGPlus);
    if (minGPlusNum !== undefined || maxGPlusNum !== undefined) {
      scoredProperties = scoredProperties.filter((p: any) => {
        if (!p.gPlus) return false;
        // Extract number from "G+5" format
        const gPlusMatch = p.gPlus.match(/G\+(\d+)/);
        if (!gPlusMatch) return false;
        const gPlusValue = parseInt(gPlusMatch[1], 10);
        if (minGPlusNum !== undefined && gPlusValue < minGPlusNum) return false;
        if (maxGPlusNum !== undefined && gPlusValue > maxGPlusNum) return false;
        return true;
      });
    }

    // Separate featured and regular properties
    const featuredActive: any[] = [];
    const regular: any[] = [];
    for (const p of scoredProperties) {
      const isFeatured = p.featured && (!p.featuredUntil || p.featuredUntil > now);
      if (isFeatured) {
        featuredActive.push(p);
      } else {
        regular.push(p);
      }
    }

    // Sort both arrays by score (descending), then by publishedAt (descending)
    featuredActive.sort((a, b) => {
      const scoreDiff = b.score.finalScore - a.score.finalScore;
      if (scoreDiff !== 0) return scoreDiff;
      const aTime = a.publishedAt?.getTime() || 0;
      const bTime = b.publishedAt?.getTime() || 0;
      return bTime - aTime;
    });

    regular.sort((a, b) => {
      const scoreDiff = b.score.finalScore - a.score.finalScore;
      if (scoreDiff !== 0) return scoreDiff;
      const aTime = a.publishedAt?.getTime() || 0;
      const bTime = b.publishedAt?.getTime() || 0;
      return bTime - aTime;
    });

    // Simple weighted interleave: 80% chance to pick featured when both available
    const featuredBias = 0.8;
    const blended: any[] = [];
    let featuredIdx = 0;
    let regularIdx = 0;

    while (featuredIdx < featuredActive.length || regularIdx < regular.length) {
      const hasFeatured = featuredIdx < featuredActive.length;
      const hasRegular = regularIdx < regular.length;
      
      const pickFeatured = hasFeatured && (!hasRegular || Math.random() < featuredBias);
      
      if (pickFeatured) {
        blended.push(featuredActive[featuredIdx++]);
      } else if (hasRegular) {
        blended.push(regular[regularIdx++]);
      }
    }

    // Count total after filtering (including G+ filter)
    const total = scoredProperties.length;
    const start = (pageNum - 1) * limitNum;
    const slice = blended.slice(start, start + limitNum);

    // Extract top featured properties for featured section (top 8 by score)
    const topFeatured = featuredActive
      .slice(0, 8)
      .map((p) => {
        const { score, ...propertyWithoutScore } = p;
        return propertyWithoutScore;
      });

    /* COMMENTED OUT: Scoring logic - re-enable after CPU issue is resolved
    // Calculate scores for all candidates using batch optimization
    const scoreStartTime = Date.now();
    const scoreMap = await calculatePropertyScoresBatch(candidates, now);
    const scoreTime = Date.now() - scoreStartTime;
    if (scoreTime > 1000) {
      console.warn(`[PERFORMANCE] Property scoring took ${scoreTime}ms for ${candidates.length} properties`);
    }

    // Attach scores to properties and separate featured/regular
    const scoredProperties = candidates.map((p) => ({
      ...p,
      score: scoreMap.get(p.id) || {
        finalScore: 0,
        featuredBoost: 0,
        engagementScore: 0,
        recencyScore: 0,
        agentBoost: 0,
        qualityScore: 0,
        priceCompetitivenessScore: 0,
        locationPopularityScore: 0,
      },
    }));

    // Separate featured and regular properties
    const featuredActive: any[] = [];
    const regular: any[] = [];
    for (const p of scoredProperties) {
      if (isFeaturedActive(p, now)) {
        featuredActive.push(p);
      } else {
        regular.push(p);
      }
    }

    // Sort both arrays by score (descending), then by publishedAt (descending)
    featuredActive.sort((a, b) => {
      const scoreDiff = b.score.finalScore - a.score.finalScore;
      if (scoreDiff !== 0) return scoreDiff;
      const aTime = a.publishedAt?.getTime() || 0;
      const bTime = b.publishedAt?.getTime() || 0;
      return bTime - aTime;
    });

    regular.sort((a, b) => {
      const scoreDiff = b.score.finalScore - a.score.finalScore;
      if (scoreDiff !== 0) return scoreDiff;
      const aTime = a.publishedAt?.getTime() || 0;
      const bTime = b.publishedAt?.getTime() || 0;
      return bTime - aTime;
    });

    // Deterministic shuffle per time bucket + page to avoid flicker but still rotate
    // Apply light shuffle within score bands to add variety
    const bucket = Math.floor(now.getTime() / (15 * 60 * 1000)); // 15-min bucket
    const deviceSeed =
      getUserId(req) ||
      req.ip ||
      req.headers['x-forwarded-for']?.toString() ||
      req.headers['user-agent'] ||
      'guest';
    const rng = createSeededRng(`${bucket}-${pageNum}-${listingType || 'ALL'}-${deviceSeed}`);

    // Light shuffle within score bands (shuffle properties with similar scores)
    const shuffleWithinBands = (arr: any[]) => {
      if (arr.length <= 1) return;
      const bandSize = Math.min(5, Math.floor(arr.length / 3)); // Shuffle in bands of 5
      for (let i = 0; i < arr.length; i += bandSize) {
        const band = arr.slice(i, i + bandSize);
        shuffleInPlace(band, rng);
        arr.splice(i, band.length, ...band);
      }
    };

    shuffleWithinBands(featuredActive);
    shuffleWithinBands(regular);

    // Weighted interleave with increased featured bias (80% chance to pick featured)
    const featuredBias = 0.8; // Increased from 0.75
    const blended: any[] = [];
    while (featuredActive.length || regular.length) {
      const pickFeatured =
        featuredActive.length > 0 &&
        (regular.length === 0 || rng() < featuredBias);
      const next = pickFeatured ? featuredActive.shift() : regular.shift();
      if (next) blended.push(next);
    }

    const start = (pageNum - 1) * limitNum;
    const slice = blended.slice(start, start + limitNum);

    const total = await prisma.property.count({ where: baseWhere });

    // Extract top featured properties for featured section (top 8 by score)
    const topFeatured = featuredActive
      .slice(0, 8)
      .map((p) => {
        // Remove score from response (optional - can keep for debugging)
        const { score, ...propertyWithoutScore } = p;
        return propertyWithoutScore;
      });
    END COMMENTED OUT */

    // Best-effort view counts for feed impressions, throttled per IP+property
    const viewerKeyBase = (req.ip || 'anon') + '|' + (getUserId(req) || 'guest');
    const viewUpdates = slice
      .map((p) => {
        const key = `${viewerKeyBase}|feed|${p.id}`;
        if (!shouldCount(recentViews, key)) return null;
        return prisma.property.update({
          where: { id: p.id },
          data: { viewCount: { increment: 1 } } as any,
        });
      })
      .filter(Boolean) as ReturnType<typeof prisma.property.update>[];

    if (viewUpdates.length > 0) {
      Promise.all(viewUpdates).catch((err) => console.error('Feed viewCount update failed', err));
    }

    // Remove score objects from response (keep properties clean)
    const propertiesWithoutScores = slice.map((p) => {
      const { score, ...propertyWithoutScore } = p;
      return propertyWithoutScore;
    });

    const result = {
      properties: propertiesWithoutScores,
      featuredProperties: topFeatured, // Top 8 featured properties by score
      pagination: {
        currentPage: pageNum,
        totalPages: Math.ceil(total / limitNum),
        totalItems: total,
        itemsPerPage: limitNum,
      },
    };
    console.timeEnd('properties-fetch');
    res.json(result);
  } catch (error: any) {
    console.timeEnd('properties-fetch');
    console.error('Get properties error:', error);
    res.status(500).json({
      error: 'Failed to fetch properties',
      message: error.message,
    });
  }
});

// Admin: get all properties with full status visibility
router.get('/admin', authenticateToken, requireAdminOrFeatures('PROPERTY_REVIEW'), async (req: AuthRequest, res: Response) => {
  try {
    // TODO: Future geo-based scoping for SUB_ADMIN (example: restrict by allowed cities/state)
    // e.g. if req.user.role === 'SUB_ADMIN', add: where.city = { in: allowedCities }

    const {
      status,
      listingType,
      serviceType,
      city,
      search,
    } = req.query;

    const where: any = {};

    if (req.user?.role === 'SUB_ADMIN' && req.userId) {
      const geoFilter = await getSubAdminGeoFilter(req.userId);
      if (geoFilter) {
        where.AND = [...(where.AND || []), geoFilter];
      }
    }

    if (
      status === 'DRAFT' ||
      status === 'PENDING' ||
      status === 'ACTIVE' ||
      status === 'SOLD' ||
      status === 'ARCHIVED' ||
      status === 'REJECTED'
    ) {
      where.status = status;
    }

    if (listingType === 'SALE' || listingType === 'RENT') {
      where.listingType = listingType;
    }

    if (serviceType === 'SELF_SERVICE' || serviceType === 'COOL_SERVICE') {
      where.serviceType = serviceType;
    }

    if (typeof city === 'string' && city.trim()) {
      where.city = city.trim();
    }

    const properties = await prisma.property.findMany({
      where,
      include: {
        owner: {
          select: {
            id: true,
            firstName: true,
            lastName: true,
            email: true,
            phone: true,
            role: true,
            verificationStatus: true,
          },
        },
        photos: {
          orderBy: [
            { isPrimary: 'desc' },
            { order: 'asc' },
          ],
          take: 1,
        },
      },
      orderBy: { createdAt: 'desc' },
      take: 500,
    });

    // Apply simple search on title / owner email / city in-memory for now
    let filtered = properties;
    if (typeof search === 'string' && search.trim()) {
      const q = search.toLowerCase();
      filtered = properties.filter((p) => {
        const ownerEmail = p.owner?.email?.toLowerCase() || '';
        const title = p.title.toLowerCase();
        const cityName = p.city.toLowerCase();
        return (
          title.includes(q) ||
          ownerEmail.includes(q) ||
          cityName.includes(q)
        );
      });
    }

    res.json({ properties: filtered });
  } catch (error: any) {
    console.error('Admin get properties error:', error);
    res.status(500).json({
      error: 'Failed to fetch properties for admin',
      message: error.message,
    });
  }
});

router.get('/:id/recommendations', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    const radiusKm = Math.max(1, Math.min(50, parseFloat((req.query.radiusKm as string) || '5')));
    const limit = Math.max(1, Math.min(24, parseInt((req.query.limit as string) || '8')));

    const summarySelect = {
      id: true,
      title: true,
      price: true,
      currency: true,
      city: true,
      subCity: true,
      latitude: true,
      longitude: true,
      bedrooms: true,
      bathrooms: true,
      areaSqft: true,
      featured: true,
      listingType: true,
      rentFrequency: true,
      photos: {
        select: { url: true, isPrimary: true },
        orderBy: [{ isPrimary: 'desc' as const }, { order: 'asc' as const }],
        take: 1,
      },
    };

    const normalize = (p: any) => {
      const { latitude: _lat, longitude: _lng, ...rest } = p || {};
      return {
        ...rest,
        price:
          typeof p?.price === 'number'
            ? p.price
            : p?.price?.toNumber?.() ?? Number(p?.price ?? 0),
      };
    };

    const base = await prisma.property.findUnique({
      where: { id },
      select: {
        id: true,
        status: true,
        city: true,
        subCity: true,
        propertyType: true,
        listingType: true,
        price: true,
        latitude: true,
        longitude: true,
      },
    });

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

    const basePrice = Number((base as any).price ?? 0);
    const priceMin = basePrice > 0 ? basePrice * 0.8 : null;
    const priceMax = basePrice > 0 ? basePrice * 1.2 : null;

    const similarWhere: any = {
      status: 'ACTIVE',
      id: { not: id },
      listingType: base.listingType,
      propertyType: base.propertyType,
      city: base.city,
    };
    if (base.subCity) {
      similarWhere.subCity = base.subCity;
    }

    const similarCandidates = await prisma.property.findMany({
      where: similarWhere,
      select: summarySelect,
      orderBy: [{ featured: 'desc' }, { publishedAt: 'desc' }],
      take: Math.min(80, limit * 10),
    });

    const similar = similarCandidates
      .filter((p) => {
        if (priceMin == null || priceMax == null) return true;
        const pPrice = Number((p as any).price ?? 0);
        if (!pPrice) return true;
        return pPrice >= priceMin && pPrice <= priceMax;
      })
      .slice(0, limit)
      .map(normalize);

    let nearby: any[] = [];
    if (typeof base.latitude === 'number' && typeof base.longitude === 'number') {
      const lat = base.latitude;
      const lng = base.longitude;
      const dLat = radiusKm / 111;
      const dLng = radiusKm / (111 * Math.max(0.1, Math.cos((lat * Math.PI) / 180)));

      const nearbyCandidates = await prisma.property.findMany({
        where: {
          status: 'ACTIVE',
          id: { not: id },
          latitude: { not: null, gte: lat - dLat, lte: lat + dLat },
          longitude: { not: null, gte: lng - dLng, lte: lng + dLng },
        },
        select: summarySelect,
        take: Math.min(120, limit * 15),
      });

      nearby = nearbyCandidates
        .map((p) => {
          const plat = Number((p as any).latitude);
          const plng = Number((p as any).longitude);
          const distKm = haversineKm({ lat, lng }, { lat: plat, lng: plng });
          return { p, distKm };
        })
        .filter((x) => Number.isFinite(x.distKm) && x.distKm <= radiusKm)
        .sort((a, b) => a.distKm - b.distKm)
        .map((x) => normalize(x.p))
        .slice(0, limit);
    } else {
      const fallbackNearby = await prisma.property.findMany({
        where: {
          status: 'ACTIVE',
          id: { not: id },
          city: base.city,
          ...(base.subCity ? { subCity: base.subCity } : {}),
        },
        select: summarySelect,
        orderBy: [{ featured: 'desc' }, { publishedAt: 'desc' }],
        take: limit,
      });
      nearby = fallbackNearby.map(normalize);
    }

    res.json({ similar, nearby });
  } catch (error: any) {
    console.error('Get property recommendations error:', error);
    res.status(500).json({
      error: 'Failed to fetch property recommendations',
      message: error.message,
    });
  }
});

// Get single property by ID
router.get('/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params;
    
    // Try to get user from token (optional - for owner/admin check)
    let userId: string | undefined;
    let userRole: string | undefined;
    try {
      const authHeader = req.headers['authorization'];
      const token = authHeader && authHeader.split(' ')[1];
      if (token) {
        const secret = process.env.JWT_SECRET || 'your-secret-key-change-in-production';
        const decoded = jwt.verify(token, secret) as { userId: string; role: string };
        userId = decoded.userId;
        userRole = decoded.role;
      }
    } catch {
      // Not authenticated or invalid token - that's fine for public access
    }

    const property = await prisma.property.findUnique({
      where: { id },
      include: {
        photos: {
          orderBy: { order: 'asc' },
        },
        amenities: true,
        owner: {
          select: {
            id: true,
            firstName: true,
            lastName: true,
            email: true,
            phone: true,
          },
        },
        _count: {
          select: {
            favorites: true,
          },
        },
      },
    });

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

    // Only show ACTIVE properties to public, but allow owners/admins to see their own properties
    const isOwner = userId && property.ownerId === userId;
    const isAdmin = userRole === 'ADMIN';
    
    if (property.status !== 'ACTIVE' && !isOwner && !isAdmin) {
      return res.status(404).json({ 
        error: 'Property not found',
        message: 'This property is not currently available for viewing.',
      });
    }

    // Privacy: control contact info visibility based on contactMethod and role
    const safeOwner = property.owner
      ? {
          id: property.owner.id,
          firstName: property.owner.firstName,
          lastName: property.owner.lastName,
          // Email remains hidden from regular buyers for now
          email: isOwner || isAdmin ? property.owner.email : null,
          // Phone is visible to owner/admin OR when seller chose PHONE_AND_CHAT
          phone:
            isOwner || isAdmin || property.contactMethod === 'PHONE_AND_CHAT'
              ? property.owner.phone
              : null,
        }
      : null;

    // Increment click count (detail views), throttled per IP+user+property
    const clickKey = `${req.ip || 'anon'}|${getUserId(req) || 'guest'}|click|${id}`;
    if (shouldCount(recentClicks, clickKey)) {
      prisma.property
        .update({
          where: { id },
          data: { clickCount: { increment: 1 } } as any,
        })
        .catch((err) => console.error('Increment clickCount failed:', err));
    }

    res.json({ property: { ...property, owner: safeOwner } });
  } catch (error: any) {
    console.error('Get property error:', error);
    res.status(500).json({
      error: 'Failed to fetch property',
      message: error.message,
    });
  }
});

export default router;







