import { NextFunction, Response } from 'express';
import { RowDataPacket } from 'mysql2/promise';
import { pool } from '../config/db.js';
import { AuthRequest } from '../middleware/auth.middleware.js';

interface NotificationRow extends RowDataPacket {
  id: number;
  type: string;
  title: string;
  message: string;
  link: string | null;
  related_project_id: number | null;
  is_read: number;
  created_at: string;
}

function toDto(row: NotificationRow) {
  return {
    id: row.id,
    type: row.type,
    title: row.title,
    message: row.message,
    link: row.link,
    relatedProjectId: row.related_project_id,
    isRead: !!row.is_read,
    createdAt: row.created_at,
  };
}

export async function list(req: AuthRequest, res: Response, next: NextFunction) {
  try {
    const unreadOnly = req.query.unreadOnly === 'true';
    const [rows] = await pool.query<NotificationRow[]>(
      `SELECT * FROM notifications WHERE user_id = ? ${unreadOnly ? 'AND is_read = 0' : ''} ORDER BY created_at DESC LIMIT 100`,
      [req.userId],
    );
    res.json(rows.map(toDto));
  } catch (err) {
    next(err);
  }
}

export async function unreadCount(req: AuthRequest, res: Response, next: NextFunction) {
  try {
    const [rows] = await pool.query<RowDataPacket[]>(
      'SELECT COUNT(*) AS count FROM notifications WHERE user_id = ? AND is_read = 0',
      [req.userId],
    );
    res.json({ count: Number(rows[0]?.count ?? 0) });
  } catch (err) {
    next(err);
  }
}

export async function markRead(req: AuthRequest, res: Response, next: NextFunction) {
  try {
    await pool.query('UPDATE notifications SET is_read = 1 WHERE id = ? AND user_id = ?', [
      req.params.id,
      req.userId,
    ]);
    res.status(204).send();
  } catch (err) {
    next(err);
  }
}

export async function markAllRead(req: AuthRequest, res: Response, next: NextFunction) {
  try {
    await pool.query('UPDATE notifications SET is_read = 1 WHERE user_id = ? AND is_read = 0', [req.userId]);
    res.status(204).send();
  } catch (err) {
    next(err);
  }
}
