import { Router, Response } from 'express';
import { requireAuth, AuthRequest } from '../../middleware/auth.middleware';
import { ShopService } from '../../services/shop.service';

const router = Router();

// All public shop routes require authentication (consistent with other game routes)
router.use(requireAuth);

// ─── Products ────────────────────────────────────────────────

router.get('/products', async (req: AuthRequest, res: Response) => {
  try {
    const { category, search } = req.query;
    const page = parseInt(req.query.page as string) || 1;
    const limit = parseInt(req.query.limit as string) || 20;

    const result = await ShopService.getProducts(
      category as string,
      search as string,
      page,
      limit,
    );
    res.json(result);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

router.get('/products/:id', async (req: AuthRequest, res: Response) => {
  try {
    const product = await ShopService.getProduct(req.params.id);
    if (!product) {
      res.status(404).json({ error: 'Produit introuvable' });
      return;
    }
    res.json(product);
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

// ─── Purchase ─────────────────────────────────────────────────

/**
 * POST /shop/purchase
 * Buy a shop product using Dagaz (premium currency).
 */
router.post('/purchase', async (req: AuthRequest, res: Response) => {
  try {
    const playerId = req.playerId!;
    const { product_id, quantity } = req.body;
    const qty = Number(quantity) || 1;

    if (!product_id) {
      res.status(400).json({ error: 'product_id requis' });
      return;
    }

    const product = await ShopService.getProduct(product_id);
    if (!product) {
      res.status(404).json({ error: 'Produit introuvable ou indisponible' });
      return;
    }

    // Check stock
    if (product.stock < qty) {
      res.status(400).json({ error: `Stock insuffisant (disponible: ${product.stock})` });
      return;
    }

    const totalCost = product.price * qty;

    // Check Dagaz balance
    const { AppDataSource } = await import('../../config/database');
    const { PlayerBalances } = await import('../../models/PlayerBalances');
    const { PlayerInventory } = await import('../../models/PlayerInventory');
    const { Order } = await import('../../models/Order');

    const balRepo = AppDataSource.getRepository(PlayerBalances);
    const invRepo = AppDataSource.getRepository(PlayerInventory);

    const balances = await balRepo.findOne({ where: { player_id: playerId } });
    if (!balances || balances.dagaz < totalCost) {
      res.status(400).json({ error: `Dagaz insuffisants. Coût: ${totalCost} ᛞ, Disponible: ${balances?.dagaz ?? 0}` });
      return;
    }

    // Deduct Dagaz
    balances.dagaz -= totalCost;
    await balRepo.save(balances);

    // Decrease stock
    const productRepo = AppDataSource.getRepository(product.constructor as any);
    product.stock -= qty;
    if (product.stock <= 0) (product as any).status = 'epuise';
    await productRepo.save(product);

    // Add to player inventory
    const invItemType = (product.category === 'special' ? 'other' : product.category) as any;
    let inv = await invRepo.findOne({
      where: { player_id: playerId, item_type: invItemType, item_subtype: product.name },
    });
    if (inv) {
      inv.quantity += qty;
    } else {
      inv = invRepo.create({
        player_id: playerId,
        item_type: invItemType,
        item_subtype: product.name,
        quantity: qty,
        weight_grams: 0,
        storage_condition: 'stored',
      });
    }
    await invRepo.save(inv);

    // Create order record
    try {
      const orderRepo = AppDataSource.getRepository(Order);
      await orderRepo.save(orderRepo.create({
        player_id: playerId,
        product_name: product.name,
        quantity: qty,
        total_price: totalCost,
        status: 'livre',
      }));
    } catch { /* Order model might not have all fields — non-blocking */ }

    res.json({
      success: true,
      purchased: { product: product.name, quantity: qty, total_cost: totalCost },
      dagaz_remaining: balances.dagaz,
    });
  } catch (err: any) {
    res.status(500).json({ error: err.message });
  }
});

export default router;
