import { pool } from '../config/database';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

export interface Notification extends RowDataPacket {
  id: number;
  user_id: number;
  type: string;
  title: string;
  message: string;
  is_read: boolean;
  created_at: Date;
}

export const findByUser = async (userId: number): Promise<Notification[]> => {
  const [rows] = await pool.query<Notification[]>('SELECT * FROM notifications WHERE user_id = ? ORDER BY created_at DESC', [userId]);
  return rows;
};

export const countUnread = async (userId: number): Promise<number> => {
  const [rows] = await pool.query('SELECT COUNT(*) as count FROM notifications WHERE user_id = ? AND is_read = FALSE', [userId]);
  return (rows as any)[0].count;
};

export const create = async (data: any, connection?: any): Promise<number> => {
  const db = connection || pool;
  const query = `
    INSERT INTO notifications 
    (user_id, type, title, message)
    VALUES (?, ?, ?, ?)
  `;
  const [result] = await (db as any).query(query, [
    data.user_id,
    data.type,
    data.title,
    data.message
  ]);
  return (result as ResultSetHeader).insertId;
};

export const markAsRead = async (id: number, userId: number): Promise<void> => {
  await pool.query('UPDATE notifications SET is_read = TRUE WHERE id = ? AND user_id = ?', [id, userId]);
};

export const markAllAsRead = async (userId: number): Promise<void> => {
  await pool.query('UPDATE notifications SET is_read = TRUE WHERE user_id = ?', [userId]);
};

export const findById = async (id: number): Promise<Notification | null> => {
  const [rows] = await pool.query<Notification[]>('SELECT * FROM notifications WHERE id = ?', [id]);
  return rows[0] || null;
};

export const remove = async (id: number): Promise<void> => {
  await pool.query('DELETE FROM notifications WHERE id = ?', [id]);
};
