import { Request, Response } from 'express';
import { supabase } from '../config/supabase.js';



// Send a message
export const sendMessage = async (req: Request, res: Response) => {
    try {
        const { toUserId, message } = req.body;
        const fromUserId = req.appUser?.id;
        const organizationId = req.headers['x-organization-id'] as string;

        if (!organizationId) {
            return res.status(400).json({ error: 'Organização não selecionada.' });
        }

        if (!toUserId || !message) {
            return res.status(400).json({ error: 'Destinatário e mensagem são obrigatórios.' });
        }

        const { data, error } = await supabase
            .from('messages')
            .insert({
                organization_id: organizationId,
                from_user_id: fromUserId,
                to_user_id: toUserId,
                message,
                is_read: false
            })
            .select()
            .single();

        if (error) throw error;
        res.status(201).json(data);
    } catch (error: any) {
        console.error('Error sending message:', error);
        res.status(500).json({ error: 'Erro ao enviar mensagem.' });
    }
};

// Get unread messages for current user
export const getUnreadMessages = async (req: Request, res: Response) => {
    try {
        const toUserId = req.appUser?.id;
        const organizationId = req.headers['x-organization-id'] as string;

        if (!organizationId) {
            return res.status(400).json({ error: 'Organização não selecionada.' });
        }

        const { data, error } = await supabase
            .from('messages')
            .select('*')
            .eq('organization_id', organizationId)
            .eq('to_user_id', toUserId)
            .eq('is_read', false)
            .eq('is_archived', false);

        if (error && error.code !== '42P01') throw error;
        res.json(data || []);
    } catch (error: any) {
        console.error('Error getting unread messages:', error);
        res.status(500).json({ error: 'Erro ao buscar mensagens.' });
    }
};

// Mark message as read
export const markMessageAsRead = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const userId = req.appUser?.id;
        const organizationId = req.headers['x-organization-id'] as string;

        const { data, error } = await supabase
            .from('messages')
            .update({ is_read: true, read_at: new Date().toISOString() })
            .eq('id', id)
            .eq('to_user_id', userId)
            .eq('organization_id', organizationId)
            .select()
            .single();

        if (error) throw error;
        res.json(data);
    } catch (error: any) {
        console.error('Error marking message as read:', error);
        res.status(500).json({ error: 'Erro ao marcar mensagem como lida.' });
    }
};

// Get my pending (unread) sent messages
export const getMyPendingMessages = async (req: Request, res: Response) => {
    try {
        const fromUserId = req.appUser?.id;
        const organizationId = req.headers['x-organization-id'] as string;

        const { data, error } = await supabase
            .from('messages')
            .select('*')
            .eq('organization_id', organizationId)
            .eq('from_user_id', fromUserId)
            .eq('is_read', false);

        if (error && error.code !== '42P01') throw error;
        res.json(data || []);
    } catch (error: any) {
        console.error('Error getting pending messages:', error);
        res.status(500).json({ error: 'Erro ao buscar mensagens pendentes.' });
    }
};

// Delete a message
export const deleteMessage = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const userId = req.appUser?.id;
        const organizationId = req.headers['x-organization-id'] as string;

        const { error } = await supabase
            .from('messages')
            .delete()
            .eq('id', id)
            .eq('from_user_id', userId)
            .eq('organization_id', organizationId)
            .eq('is_read', false);

        if (error) throw error;
        res.status(204).send();
    } catch (error: any) {
        console.error('Error deleting message:', error);
        res.status(500).json({ error: 'Erro ao deletar mensagem.' });
    }
};

// Recipient archives a message
export const archiveMessage = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const userId = req.appUser?.id;
        const organizationId = req.headers['x-organization-id'] as string;

        const { data, error } = await supabase
            .from('messages')
            .update({ is_archived: true, is_read: true })
            .eq('id', id)
            .eq('to_user_id', userId)
            .eq('organization_id', organizationId)
            .select()
            .single();

        if (error) throw error;
        res.json(data);
    } catch (error: any) {
        console.error('Error archiving message:', error);
        res.status(500).json({ error: 'Erro ao arquivar mensagem.' });
    }
};

export const recipientDeleteMessage = async (req: Request, res: Response) => {
    try {
        const { id } = req.params;
        const userId = req.appUser?.id;
        const organizationId = req.headers['x-organization-id'] as string;

        const { data, error } = await supabase
            .from('messages')
            .update({ 'is_deleted_by_recipient': true })
            .eq('id', id)
            .eq('to_user_id', userId)
            .eq('organization_id', organizationId)
            .select()
            .single();

        if (error) throw error;
        res.json({ message: 'Mensagem excluída com sucesso.' });
    } catch (error: any) {
        console.error('Error deleting message:', error);
        res.status(500).json({ error: 'Erro ao excluir mensagem.' });
    }
};