import pool from '../config/database';

export interface Banner {
  id: string;
  message: string;
  level: 'info' | 'important' | 'critical';
  show_as: 'banner' | 'widget';
  starts_at: string;
  ends_at: string | null;
  created_by: string | null;
  created_at: string;
}

export interface CreateBannerInput {
  message: string;
  level: 'info' | 'important' | 'critical';
  show_as?: 'banner' | 'widget';
  starts_at?: string;
  ends_at?: string | null;
}

class BannerService {
  async getActive(): Promise<Banner[]> {
    const result = await pool.query(
      `SELECT * FROM announcement_banners
       WHERE starts_at <= NOW()
         AND (ends_at IS NULL OR ends_at > NOW())
       ORDER BY
         CASE level WHEN 'critical' THEN 0 WHEN 'important' THEN 1 ELSE 2 END,
         created_at DESC`
    );
    return result.rows;
  }

  async getAll(): Promise<Banner[]> {
    const result = await pool.query(
      'SELECT * FROM announcement_banners ORDER BY created_at DESC'
    );
    return result.rows;
  }

  async create(data: CreateBannerInput, userId: string): Promise<Banner> {
    const result = await pool.query(
      `INSERT INTO announcement_banners (message, level, show_as, starts_at, ends_at, created_by)
       VALUES ($1, $2, $3, $4, $5, $6) RETURNING *`,
      [data.message, data.level, data.show_as ?? 'banner', data.starts_at ?? new Date().toISOString(), data.ends_at ?? null, userId]
    );
    return result.rows[0];
  }

  async delete(id: string): Promise<boolean> {
    const result = await pool.query(
      'DELETE FROM announcement_banners WHERE id = $1',
      [id]
    );
    return (result.rowCount ?? 0) > 0;
  }
}

export default new BannerService();
