import { Router, Request, Response } from 'express';
import { validate } from '../middleware/validate';
import { publicLimiter } from '../middleware/rateLimits';
import { AvailabilityQuerySchema, CreateAppointmentSchema, BOOKING } from '@nobel/shared';
import {
  getAvailability,
  createPublicAppointment,
  toDateOnly,
  localToday,
} from '../services/appointments.service';
import prisma from '../lib/prisma';

const router = Router();
router.use(publicLimiter);

router.get('/shop', async (_req: Request, res: Response) => {
  const shop = await prisma.shop.findFirst();
  if (!shop) { res.status(404).json({ error: 'Shop not configured' }); return; }
  res.json({
    name: shop.name,
    address: shop.address,
    phone: shop.phone,
    email: shop.email,
    openHour: shop.openHour,
    closeHour: shop.closeHour,
    openDays: BOOKING.openDays,
    slots: BOOKING.slots,
  });
});

router.get('/services', async (_req: Request, res: Response) => {
  const services = await prisma.serviceCatalogItem.findMany({
    where: { active: true },
    orderBy: [{ sortOrder: 'asc' }, { name: 'asc' }],
    select: {
      id: true, slug: true, name: true, description: true,
      category: true, price: true, durationMin: true,
    },
  });
  res.json(services);
});

router.get('/availability', validate(AvailabilityQuerySchema, 'query'), async (req: Request, res: Response) => {
  const { from, days } = req.query as unknown as { from?: string; days: number };
  const fromStr = from ?? localToday();
  const availability = await getAvailability(fromStr, days);
  res.json(availability);
});

router.post('/appointments', validate(CreateAppointmentSchema), async (req: Request, res: Response) => {
  const appt = await createPublicAppointment(req.body);
  // Public response: enough to show a confirmation, no internal ids
  res.status(201).json({
    no: appt.no,
    date: toDateOnly(appt.date),
    slot: appt.slot,
    status: appt.status,
    service: appt.service,
  });
});

export default router;
