import { Request, Response } from 'express';
import db from '../../database/models/index.js';
const { EmailTemplate, Notification } = db;
import { AuthRequest } from '../../types/express.types.js';

export const getTemplates = async (req: Request, res: Response) => {
    try {
        const templates = await EmailTemplate.findAll({ where: { isActive: true } });
        res.json({ success: true, data: templates });
    } catch (error) {
        console.error('Get email templates error:', error);
        res.status(500).json({ success: false, message: 'Error fetching templates' });
    }
};

export const createTemplate = async (req: AuthRequest, res: Response) => {
    try {
        const { code, description, subject, body, placeholders } = req.body;
        const template = await EmailTemplate.create({ code, description, subject, body, placeholders });
        res.status(201).json({ success: true, data: template });
    } catch (error) {
        res.status(500).json({ success: false, message: 'Error creating template' });
    }
};

export const getNotifications = async (req: AuthRequest, res: Response) => {
    try {
        const page = parseInt(req.query.page as string) || 1;
        const limit = parseInt(req.query.limit as string) || 50;
        const offset = (page - 1) * limit;

        const { count, rows } = await Notification.findAndCountAll({
            where: { userId: req.user?.id },
            order: [['createdAt', 'DESC']],
            limit,
            offset
        });

        const totalPages = Math.ceil(count / limit);

        const unreadCount = await Notification.count({
            where: { userId: req.user?.id, isRead: false }
        });

        res.json({ 
            success: true, 
            data: rows,
            pagination: {
                totalElements: count,
                totalPages,
                currentPage: page,
                pageSize: limit,
                unreadCount
            }
        });
    } catch (error) {
        res.status(500).json({ success: false, message: 'Error fetching notifications' });
    }
};

export const updatePushSubscription = async (req: AuthRequest, res: Response) => {
    try {
        const { subscription } = req.body;
        const userId = req.user?.id;

        if (!subscription || !subscription.endpoint) {
            return res.status(400).json({ success: false, message: 'Invalid subscription data' });
        }

        const { endpoint, keys } = subscription;

        await db.PushSubscription.upsert({
            userId,
            endpoint,
            p256dh: keys.p256dh,
            auth: keys.auth,
            userAgent: req.get('user-agent')
        });

        res.json({ success: true, message: 'Push subscription updated' });
    } catch (error) {
        console.error('Push subscription error:', error);
        res.status(500).json({ success: false, message: 'Error updating push subscription' });
    }
};

export const markAsRead = async (req: AuthRequest, res: Response) => {
    try {
        const { id } = req.params;
        await Notification.update({ isRead: true }, {
            where: { id, userId: req.user?.id }
        });
        res.json({ success: true, message: 'Notification marked as read' });
    } catch (error) {
        res.status(500).json({ success: false, message: 'Error updating notification' });
    }
};

export const markAllAsRead = async (req: AuthRequest, res: Response) => {
    try {
        await Notification.update({ isRead: true }, {
            where: { userId: req.user?.id, isRead: false }
        });
        res.json({ success: true, message: 'All notifications marked as read' });
    } catch (error) {
        res.status(500).json({ success: false, message: 'Error updating notifications' });
    }
};
