import { supabase } from '@/integrations/supabase/client';
import { format } from 'date-fns';

/**
 * Fetches comprehensive activity data for a homeowner request
 * Includes votes and comments to build a timeline
 */
export async function fetchHomeownerRequestActivity(requestId) {
    try {
        const { data: votes, error: votesError } = await supabase
            .from('homeowner_request_votes')
            .select('*, user:users(full_name, email)')
            .eq('request_id', requestId);
            
        if (votesError) throw votesError;

        const { data: comments, error: commentsError } = await supabase
            .from('homeowner_request_comments')
            .select('*, user:users(full_name, email)')
            .eq('request_id', requestId);
            
        if (commentsError) throw commentsError;

        const timeline = [];
        
        votes?.forEach(v => timeline.push({
            id: `vote-${v.id}`,
            type: 'vote',
            date: new Date(v.created_at),
            user: v.user,
            details: `Voted ${v.vote === 'approve' ? 'Approve' : 'Deny'}`,
            rawVote: v.vote
        }));

        comments?.forEach(c => timeline.push({
            id: `comment-${c.id}`,
            type: 'comment',
            date: new Date(c.created_at),
            user: c.user,
            details: c.is_system_generated 
                ? c.content 
                : `Commented: "${c.content.substring(0, 60)}${c.content.length > 60 ? '...' : ''}"`,
            isSystem: c.is_system_generated
        }));

        timeline.sort((a, b) => b.date - a.date);

        return {
            votes: votes || [],
            comments: comments || [],
            timeline
        };
    } catch (error) {
        console.error("Error in fetchHomeownerRequestActivity:", error);
        return { votes: [], comments: [], timeline: [] };
    }
}

/**
 * Fetches comprehensive activity data for a bid/quote
 * Includes votes, comments, and tags
 */
export async function fetchBidQuoteActivity(bidId) {
    try {
        const { data: votes, error: votesError } = await supabase
            .from('bid_quote_votes')
            .select('*, user:users(full_name, email)')
            .eq('bid_quote_id', bidId);

        if (votesError) throw votesError;

        const { data: comments, error: commentsError } = await supabase
            .from('bid_quote_comments')
            .select('*, user:users(full_name, email)')
            .eq('bid_quote_id', bidId);
            
        if (commentsError) throw commentsError;

        const { data: tags, error: tagsError } = await supabase
            .from('bid_quote_tags')
            .select('*')
            .eq('bid_quote_id', bidId);
            
        if (tagsError) throw tagsError;

        const timeline = [];

        votes?.forEach(v => timeline.push({
            id: `vote-${v.id}`,
            type: 'vote',
            date: new Date(v.created_at),
            user: v.user,
            details: `Voted ${v.vote === 'upvote' ? 'Upvote' : 'Downvote'}`,
            rawVote: v.vote
        }));

        comments?.forEach(c => timeline.push({
            id: `comment-${c.id}`,
            type: 'comment',
            date: new Date(c.created_at),
            user: c.user,
            details: `Commented: "${c.comment_text.substring(0, 60)}${c.comment_text.length > 60 ? '...' : ''}"`
        }));
        
        tags?.forEach(t => timeline.push({
            id: `tag-${t.id}`,
            type: 'tag',
            date: new Date(t.created_at),
            user: null, 
            details: `Tag added: ${t.tag_name}`,
            color: t.color
        }));

        timeline.sort((a, b) => b.date - a.date);

        return {
            votes: votes || [],
            tags: tags || [],
            comments: comments || [],
            timeline
        };
    } catch (error) {
        console.error("Error in fetchBidQuoteActivity:", error);
        return { votes: [], tags: [], comments: [], timeline: [] };
    }
}
