import { Request, Response } from 'express';
import { z } from 'zod';
import bannerService from '../services/banner.service';
import logger from '../utils/logger';

const createSchema = z.object({
  message: z.string().min(1).max(2000),
  level: z.enum(['info', 'important', 'critical']).default('info'),
  show_as: z.enum(['banner', 'widget']).default('banner'),
  starts_at: z.string().datetime().optional(),
  ends_at: z.string().datetime().nullable().optional(),
});

class BannerController {
  async getActive(_req: Request, res: Response): Promise<void> {
    try {
      const banners = await bannerService.getActive();
      res.json({ success: true, data: banners });
    } catch (error) {
      logger.error('Failed to get banners', { error });
      res.status(500).json({ success: false, message: 'Failed to get banners' });
    }
  }

  async getAll(_req: Request, res: Response): Promise<void> {
    try {
      const banners = await bannerService.getAll();
      res.json({ success: true, data: banners });
    } catch (error) {
      logger.error('Failed to get all banners', { error });
      res.status(500).json({ success: false, message: 'Failed to get banners' });
    }
  }

  async create(req: Request, res: Response): Promise<void> {
    try {
      const data = createSchema.parse(req.body);
      const banner = await bannerService.create(data, req.user!.id);
      res.status(201).json({ success: true, data: banner });
    } catch (error) {
      if (error instanceof z.ZodError) {
        res.status(400).json({ success: false, message: 'Invalid input', errors: error.issues });
        return;
      }
      logger.error('Failed to create banner', { error });
      res.status(500).json({ success: false, message: 'Failed to create banner' });
    }
  }

  async delete(req: Request, res: Response): Promise<void> {
    try {
      const deleted = await bannerService.delete(req.params.id as string);
      if (!deleted) {
        res.status(404).json({ success: false, message: 'Banner not found' });
        return;
      }
      res.json({ success: true });
    } catch (error) {
      logger.error('Failed to delete banner', { error });
      res.status(500).json({ success: false, message: 'Failed to delete banner' });
    }
  }
}

export default new BannerController();
