import { Router, type IRouter } from "express";
import { db, locationsTable } from "@workspace/db";
import { eq, and, ilike } from "drizzle-orm";
import { requireAuth } from "../middlewares/auth";
import { ListLocationsQueryParams, GetLocationParams } from "@workspace/api-zod";

const router: IRouter = Router();

router.get("/locations", requireAuth, async (req, res): Promise<void> => {
  const params = ListLocationsQueryParams.safeParse(req.query);
  const filters = [eq(locationsTable.isActive, true)];

  if (params.success) {
    if (params.data.type) {
      filters.push(eq(locationsTable.type, params.data.type as "hotel" | "venue" | "safehouse"));
    }
    if (params.data.city) {
      filters.push(ilike(locationsTable.city, `%${params.data.city}%`));
    }
  }

  const locations = await db.select().from(locationsTable).where(and(...filters));
  res.json(locations.map(l => ({
    id: l.id, name: l.name, city: l.city, type: l.type, rating: l.rating,
    photoUrl: l.photoUrl, description: l.description, address: l.address,
    isFeatured: l.isFeatured, isActive: l.isActive, createdAt: l.createdAt,
  })));
});

router.get("/locations/:id", requireAuth, async (req, res): Promise<void> => {
  const params = GetLocationParams.safeParse({ id: req.params.id });
  if (!params.success) {
    res.status(400).json({ error: "Invalid ID" });
    return;
  }
  const [location] = await db.select().from(locationsTable).where(eq(locationsTable.id, params.data.id));
  if (!location) {
    res.status(404).json({ error: "Location not found" });
    return;
  }
  res.json({
    id: location.id, name: location.name, city: location.city, type: location.type, rating: location.rating,
    photoUrl: location.photoUrl, description: location.description, address: location.address,
    isFeatured: location.isFeatured, isActive: location.isActive, createdAt: location.createdAt,
  });
});

export default router;
