import { Request, Response } from "express";
import { ZoneModel, Zone } from "../models/zoneModel";

export const zoneController = {
    // GET /api/zones
    getAll: async (_req: Request, res: Response): Promise<void> => {
        try {
            const zones = await ZoneModel.findAll();
            res.json({ success: true, data: zones });
        } catch (err) {
            res.status(500).json({ success: false, error: "Error al obtener zonas" });
        }
    },

    // GET /api/zones/:id
    getById: async (req: Request, res: Response): Promise<void> => {
        try {
            const id = parseInt(req.params.id);
            const zone = await ZoneModel.findById(id);
            if (!zone) { res.status(404).json({ success: false, error: "Zona no encontrada" }); return; }
            res.json({ success: true, data: zone });
        } catch (err) {
            res.status(500).json({ success: false, error: "Error al obtener zona" });
        }
    },

    // GET /api/zones/active
    getActive: async (_req: Request, res: Response): Promise<void> => {
        try {
            const zones = await ZoneModel.findActive();
            res.json({ success: true, data: zones });
        } catch (err) {
            res.status(500).json({ success: false, error: "Error" });
        }
    },

    // POST /api/zones
    create: async (req: Request, res: Response): Promise<void> => {
        try {
            const { name, slug, lat, lng, radius_km, active, pisos_slug, thinkspain_slug, globaliza_slug } = req.body;
            if (!name || !lat || !lng) {
                res.status(400).json({ success: false, error: "Nombre, latitud y longitud son obligatorios" });
                return;
            }
            const zone: Zone = {
                name: String(name).trim(),
                slug: String(slug || "").trim() || name.toLowerCase().normalize("NFD")
                    .replace(/[̀-ͯ]/g, "").replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, ""),
                lat: parseFloat(lat),
                lng: parseFloat(lng),
                radius_km: radius_km ? parseFloat(radius_km) : 10,
                active: active === "0" ? 0 : 1,
                pisos_slug: pisos_slug ? String(pisos_slug).trim() || undefined : undefined,
                thinkspain_slug: thinkspain_slug ? String(thinkspain_slug).trim() || null : null,
                globaliza_slug: globaliza_slug ? String(globaliza_slug).trim() || null : null,
            };
            const id = await ZoneModel.create(zone);
            const created = await ZoneModel.findById(id);
            res.json({ success: true, data: created });
        } catch (err) {
            res.status(500).json({ success: false, error: "Error al crear zona" });
        }
    },

    // PUT /api/zones/:id
    update: async (req: Request, res: Response): Promise<void> => {
        try {
            const id = parseInt(req.params.id);
            await ZoneModel.update(id, req.body);
            const updated = await ZoneModel.findById(id);
            res.json({ success: true, data: updated });
        } catch (err) {
            res.status(500).json({ success: false, error: "Error al actualizar zona" });
        }
    },

    // PATCH /api/zones/:id/toggle
    toggle: async (req: Request, res: Response): Promise<void> => {
        try {
            const id = parseInt(req.params.id);
            await ZoneModel.toggleActive(id);
            const updated = await ZoneModel.findById(id);
            res.json({ success: true, data: updated });
        } catch (err) {
            res.status(500).json({ success: false, error: "Error al cambiar estado" });
        }
    },

    // DELETE /api/zones/:id
    delete: async (req: Request, res: Response): Promise<void> => {
        try {
            const id = parseInt(req.params.id);
            await ZoneModel.deleteById(id);
            res.json({ success: true, message: "Zona eliminada" });
        } catch (err) {
            res.status(500).json({ success: false, error: "Error al eliminar zona" });
        }
    },
};
