import { Router, Response } from 'express';
import { requireAuth, AuthRequest } from '../../middleware/auth.middleware';
import { PropertyService, StorageLocationType } from '../../services/property.service';
import { BusinessService } from '../../services/business.service';

const router = Router();

/** Valide et caste le parametre location_type depuis une query string */
function parseLocationType(v: any): StorageLocationType | null {
  const allowed: StorageLocationType[] = ['residence', 'business', 'warehouse', 'vehicle', 'player'];
  return allowed.includes(v) ? (v as StorageLocationType) : null;
}

// All property routes require authentication
router.use(requireAuth);

// ── Businesses ──────────────────────────────────────────────

/**
 * GET /api/property/businesses
 */
router.get('/businesses', async (req: AuthRequest, res: Response) => {
  try {
    const businesses = await PropertyService.getPlayerBusinesses(req.playerId!);
    res.json(businesses);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * GET /api/property/businesses/:id
 */
router.get('/businesses/:id', async (req: AuthRequest, res: Response) => {
  try {
    const business = await PropertyService.getBusinessById(req.params.id, req.playerId!);
    if (!business) return res.status(404).json({ error: 'Business introuvable' });
    res.json(business);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * POST /api/property/businesses
 */
router.post('/businesses', async (req: AuthRequest, res: Response) => {
  try {
    const business = await PropertyService.createBusiness(req.playerId!, req.body);
    res.status(201).json(business);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * PUT /api/property/businesses/:id
 */
router.put('/businesses/:id', async (req: AuthRequest, res: Response) => {
  try {
    const business = await PropertyService.updateBusiness(req.params.id, req.playerId!, req.body);
    if (!business) return res.status(404).json({ error: 'Business introuvable' });
    res.json(business);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * DELETE /api/property/businesses/:id
 */
router.delete('/businesses/:id', async (req: AuthRequest, res: Response) => {
  try {
    const result = await PropertyService.deleteBusiness(req.params.id, req.playerId!);
    if (!result) return res.status(404).json({ error: 'Business introuvable' });
    res.json({ message: 'Business supprimé' });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * POST /api/property/businesses/:id/purchase
 * Buy a business from Municipalite or another player
 */
router.post('/businesses/:id/purchase', async (req: AuthRequest, res: Response) => {
  try {
    const business = await PropertyService.purchaseBusiness(req.params.id, req.playerId!);
    res.json(business);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

/**
 * POST /api/property/businesses/:id/sell
 * Sell a business back (credits sale_value)
 */
router.post('/businesses/:id/sell', async (req: AuthRequest, res: Response) => {
  try {
    const business = await PropertyService.sellBusiness(req.params.id, req.playerId!);
    res.json(business);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

/**
 * POST /api/property/businesses/:id/convert
 * Convert a business to a specialized production type
 * Body: { production_type: string }
 */
router.post('/businesses/:id/convert', async (req: AuthRequest, res: Response) => {
  try {
    const { production_type } = req.body;
    if (!production_type) return res.status(400).json({ error: 'production_type requis' });
    const business = await BusinessService.convertBusiness(req.params.id, req.playerId!, production_type);
    res.json(business);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

/**
 * POST /api/property/businesses/:id/revert
 * Revert a business conversion back to base type
 */
router.post('/businesses/:id/revert', async (req: AuthRequest, res: Response) => {
  try {
    const business = await BusinessService.revertConversion(req.params.id, req.playerId!);
    res.json(business);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

/**
 * GET /api/property/businesses/:id/conversions
 * Get available conversion options for a business
 */
router.get('/businesses/:id/conversions', async (req: AuthRequest, res: Response) => {
  try {
    const business = await PropertyService.getBusinessById(req.params.id, req.playerId!);
    if (!business) return res.status(404).json({ error: 'Business introuvable' });
    const conversions = BusinessService.getAvailableConversions(business);
    res.json(conversions);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

// ── Mettre en vente (Phase 15 Iter 7.2, 19-04-2026) ─────────

/** POST /api/property/:type/:id/list-for-sale body { price_light: number } */
router.post('/:type/:id/list-for-sale', async (req: AuthRequest, res: Response) => {
  try {
    const { type, id } = req.params;
    if (!['business', 'residence', 'warehouse'].includes(type)) {
      return res.status(400).json({ error: 'type invalide (business/residence/warehouse)' });
    }
    const price = Number(req.body?.price_light);
    const out = await PropertyService.listForSale(type as any, id, req.playerId!, price);
    res.json(out);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

/** POST /api/property/:type/:id/unlist */
router.post('/:type/:id/unlist', async (req: AuthRequest, res: Response) => {
  try {
    const { type, id } = req.params;
    if (!['business', 'residence', 'warehouse'].includes(type)) {
      return res.status(400).json({ error: 'type invalide (business/residence/warehouse)' });
    }
    const out = await PropertyService.unlist(type as any, id, req.playerId!);
    res.json(out);
  } catch (err: any) { res.status(400).json({ error: err.message }); }
});

// ── Residences ─────────────────────────────────────────────

/**
 * GET /api/property/residences
 */
router.get('/residences', async (req: AuthRequest, res: Response) => {
  try {
    const residences = await PropertyService.getPlayerResidences(req.playerId!);
    res.json(residences);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * GET /api/property/residences/:id
 */
router.get('/residences/:id', async (req: AuthRequest, res: Response) => {
  try {
    const residence = await PropertyService.getResidenceById(req.params.id, req.playerId!);
    if (!residence) return res.status(404).json({ error: 'Résidence introuvable' });
    res.json(residence);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * POST /api/property/residences
 */
router.post('/residences', async (req: AuthRequest, res: Response) => {
  try {
    const residence = await PropertyService.createResidence(req.playerId!, req.body);
    res.status(201).json(residence);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * PUT /api/property/residences/:id
 */
router.put('/residences/:id', async (req: AuthRequest, res: Response) => {
  try {
    const residence = await PropertyService.updateResidence(req.params.id, req.playerId!, req.body);
    if (!residence) return res.status(404).json({ error: 'Résidence introuvable' });
    res.json(residence);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * DELETE /api/property/residences/:id
 */
router.delete('/residences/:id', async (req: AuthRequest, res: Response) => {
  try {
    const result = await PropertyService.deleteResidence(req.params.id, req.playerId!);
    if (!result) return res.status(404).json({ error: 'Résidence introuvable' });
    res.json({ message: 'Résidence supprimée' });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/** POST /api/property/residences/:id/planque-active — Set as active planque (deactivates all others) */
router.post('/residences/:id/planque-active', async (req: AuthRequest, res: Response) => {
  try {
    const residence = await PropertyService.setPlanqueActive(req.params.id, req.playerId!);
    res.json(residence);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

// ── Vehicles ───────────────────────────────────────────────

/**
 * GET /api/property/vehicles
 */
router.get('/vehicles', async (req: AuthRequest, res: Response) => {
  try {
    const vehicles = await PropertyService.getPlayerVehicles(req.playerId!);
    res.json(vehicles);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * GET /api/property/vehicles/:id
 */
router.get('/vehicles/:id', async (req: AuthRequest, res: Response) => {
  try {
    const vehicle = await PropertyService.getVehicleById(req.params.id, req.playerId!);
    if (!vehicle) return res.status(404).json({ error: 'Véhicule introuvable' });
    res.json(vehicle);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * POST /api/property/vehicles
 */
router.post('/vehicles', async (req: AuthRequest, res: Response) => {
  try {
    const vehicle = await PropertyService.createVehicle(req.playerId!, req.body);
    res.status(201).json(vehicle);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * PUT /api/property/vehicles/:id
 */
router.put('/vehicles/:id', async (req: AuthRequest, res: Response) => {
  try {
    const vehicle = await PropertyService.updateVehicle(req.params.id, req.playerId!, req.body);
    if (!vehicle) return res.status(404).json({ error: 'Véhicule introuvable' });
    res.json(vehicle);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * DELETE /api/property/vehicles/:id
 */
router.delete('/vehicles/:id', async (req: AuthRequest, res: Response) => {
  try {
    const result = await PropertyService.deleteVehicle(req.params.id, req.playerId!);
    if (!result) return res.status(404).json({ error: 'Véhicule introuvable' });
    res.json({ message: 'Véhicule supprimé' });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

// ── Warehouses ─────────────────────────────────────────────

/**
 * GET /api/property/warehouses
 */
router.get('/warehouses', async (req: AuthRequest, res: Response) => {
  try {
    const warehouses = await PropertyService.getPlayerWarehouses(req.playerId!);
    res.json(warehouses);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * GET /api/property/warehouses/:id
 */
router.get('/warehouses/:id', async (req: AuthRequest, res: Response) => {
  try {
    const warehouse = await PropertyService.getWarehouseById(req.params.id, req.playerId!);
    if (!warehouse) return res.status(404).json({ error: 'Entrepôt introuvable' });
    res.json(warehouse);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * POST /api/property/warehouses
 */
router.post('/warehouses', async (req: AuthRequest, res: Response) => {
  try {
    const warehouse = await PropertyService.createWarehouse(req.playerId!, req.body);
    res.status(201).json(warehouse);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * PUT /api/property/warehouses/:id
 */
router.put('/warehouses/:id', async (req: AuthRequest, res: Response) => {
  try {
    const warehouse = await PropertyService.updateWarehouse(req.params.id, req.playerId!, req.body);
    if (!warehouse) return res.status(404).json({ error: 'Entrepôt introuvable' });
    res.json(warehouse);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

/**
 * DELETE /api/property/warehouses/:id
 */
router.delete('/warehouses/:id', async (req: AuthRequest, res: Response) => {
  try {
    const result = await PropertyService.deleteWarehouse(req.params.id, req.playerId!);
    if (!result) return res.status(404).json({ error: 'Entrepôt introuvable' });
    res.json({ message: 'Entrepôt supprimé' });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

// ══════════════════════════════════════════════════════════════════
// ITEM TRANSFERS (audit 15-04-2026, Phase 5)
// ══════════════════════════════════════════════════════════════════

/**
 * GET /api/property/items?location_type=<type>&location_id=<uuid>
 * Liste les items stockes a une localisation du joueur.
 */
router.get('/items', async (req: AuthRequest, res: Response) => {
  try {
    const locationType = parseLocationType(req.query.location_type);
    const locationId = String(req.query.location_id || '');
    if (!locationType || !locationId) {
      return res.status(400).json({ error: 'location_type et location_id requis' });
    }
    const items = await PropertyService.listItemsAtLocation(req.playerId!, locationType, locationId);
    res.json(items);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

/**
 * GET /api/property/capacity?location_type=<type>&location_id=<uuid>
 * Retourne la capacite (total, rempli, restant) d'une localisation.
 * Le poids rempli est calcule dynamiquement via SUM(inventory).
 */
router.get('/capacity', async (req: AuthRequest, res: Response) => {
  try {
    const locationType = parseLocationType(req.query.location_type);
    const locationId = String(req.query.location_id || '');
    if (!locationType || !locationId) {
      return res.status(400).json({ error: 'location_type et location_id requis' });
    }
    const cap = await PropertyService.getCapacity(req.playerId!, locationType, locationId);
    res.json(cap);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

/**
 * POST /api/property/transfer-item
 * Body: {
 *   source_location_type: 'residence' | 'business' | 'warehouse' | 'vehicle' | 'player',
 *   source_location_id: string,           // playerId si 'player'
 *   destination_location_type: idem,
 *   destination_location_id: string,       // playerId si 'player'
 *   inventory_id: string,                   // PlayerInventory.id
 *   quantity: number
 * }
 * Transaction atomique, recalcule la storage_condition selon la destination,
 * verifie la capacite dynamique et rejette si is_listed=true.
 */
router.post('/transfer-item', async (req: AuthRequest, res: Response) => {
  try {
    const body = req.body || {};
    const srcType = parseLocationType(body.source_location_type);
    const dstType = parseLocationType(body.destination_location_type);
    if (!srcType || !dstType) {
      return res.status(400).json({ error: 'source_location_type et destination_location_type requis' });
    }
    if (!body.source_location_id || !body.destination_location_id || !body.inventory_id) {
      return res.status(400).json({ error: 'source_location_id, destination_location_id, inventory_id requis' });
    }
    const result = await PropertyService.transferItem(req.playerId!, {
      source_location_type: srcType,
      source_location_id: String(body.source_location_id),
      destination_location_type: dstType,
      destination_location_id: String(body.destination_location_id),
      inventory_id: String(body.inventory_id),
      quantity: Number(body.quantity),
    });
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

// ═══════════════════════════════════════════════════════════════
// audit 15-04-2026 Phase 13.b — Deal spot routes
// ═══════════════════════════════════════════════════════════════

/**
 * POST /api/property/residence/:id/deal-spot/activate
 * Active un point de deal fixe dans une residence (planque active requise).
 * Body: { drug_name: string }
 */
router.post('/residence/:id/deal-spot/activate', async (req: AuthRequest, res: Response) => {
  try {
    const { PointDeDealService } = await import('../../services/point-de-deal.service');
    const { drug_name } = req.body;
    if (!drug_name) return res.status(400).json({ error: 'drug_name requis' });
    const result = await PointDeDealService.activateSpot(req.playerId!, req.params.id, drug_name);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

/**
 * POST /api/property/residence/:id/deal-spot/deactivate
 * Desactive le point de deal fixe.
 */
router.post('/residence/:id/deal-spot/deactivate', async (req: AuthRequest, res: Response) => {
  try {
    const { PointDeDealService } = await import('../../services/point-de-deal.service');
    const result = await PointDeDealService.deactivateSpot(req.playerId!, req.params.id);
    res.json(result);
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

/**
 * GET /api/property/residence/:id/deal-spot
 * Retourne les infos du deal spot (actif ou non).
 */
router.get('/residence/:id/deal-spot', async (req: AuthRequest, res: Response) => {
  try {
    const { PointDeDealService } = await import('../../services/point-de-deal.service');
    const info = await PointDeDealService.getSpotInfo(req.params.id);
    res.json(info ?? { active: false });
  } catch (err: any) {
    res.status(400).json({ error: err.message });
  }
});

export default router;

