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

const DEFAULT_SETTINGS = {
    settingsId: 'global',
    appName: 'GPI',
    appSubtitle: 'Gestão de Pintura Industrial'
};

export const getSettings = async (req: Request, res: Response) => {
    try {
        const { data: settings, error } = await supabase
            .from('system_settings')
            .select('*')
            .eq('settings_id', 'global')
            .single();

        if (error && error.code !== 'PGRST116') {
            console.log('System settings table not found, returning defaults');
            return res.json(DEFAULT_SETTINGS);
        }

        res.json(settings || DEFAULT_SETTINGS);
    } catch (error) {
        console.error('Error fetching system settings:', error);
        res.json(DEFAULT_SETTINGS);
    }
};

export const updateSettings = async (req: Request, res: Response) => {
    try {
        const { appName, appSubtitle, appLogoUrl } = req.body;

        const { data: existing, error: fetchError } = await supabase
            .from('system_settings')
            .select('*')
            .eq('settings_id', 'global')
            .single();

        let settings;
        if (fetchError || !existing) {
            const { data, error } = await supabase
                .from('system_settings')
                .insert({
                    settings_id: 'global',
                    app_name: appName,
                    app_subtitle: appSubtitle,
                    app_logo_url: appLogoUrl,
                    updated_by: req.appUser?.email
                })
                .select()
                .single();

            if (error) throw error;
            settings = data;
        } else {
            const { data, error } = await supabase
                .from('system_settings')
                .update({
                    app_name: appName,
                    app_subtitle: appSubtitle,
                    app_logo_url: appLogoUrl,
                    updated_by: req.appUser?.email
                })
                .eq('id', existing.id)
                .select()
                .single();

            if (error) throw error;
            settings = data;
        }

        console.log(`⚙️ System Settings updated by ${req.appUser?.email}`);
        res.json(settings);
    } catch (error) {
        console.error('Error updating system settings:', error);
        res.status(500).json({ error: 'Erro ao atualizar configurações do sistema' });
    }
};

export const serveLogo = async (req: Request, res: Response) => {
    try {
        const { filename } = req.params as { filename: string };
        const tmpPath = path.join(os.tmpdir(), 'uploads', filename);
        const localPath = path.join(process.cwd(), 'uploads', filename);

        if (fs.existsSync(tmpPath)) {
            res.sendFile(tmpPath);
        } else if (fs.existsSync(localPath)) {
            res.sendFile(localPath);
        } else {
            console.error(`Logo file not found in tmp or local: ${filename}`);
            res.status(404).json({ error: 'Imagem não encontrada' });
        }
    } catch (error) {
        console.error('Error serving logo:', error);
        res.status(500).json({ error: 'Erro ao processar imagem' });
    }
};

export const uploadLogo = async (req: Request, res: Response) => {
    try {
        if (!req.file) {
            return res.status(400).json({ error: 'Nenhum arquivo enviado.' });
        }

        const fileUrl = `/api/system-settings/logo-image/${req.file.filename}`;
        res.json({ url: fileUrl });
    } catch (error) {
        console.error('Error uploading logo:', error);
        res.status(500).json({ error: 'Erro ao fazer upload do logo.' });
    }
};

export const getGlobalUsers = async (req: Request, res: Response) => {
    try {
        const { data: users, error } = await supabase
            .from('users')
            .select('*')
            .order('created_at', { ascending: false });
        
        if (error && error.code !== '42P01') throw error;
        res.json(users || []);
    } catch (error) {
        console.error('Error getting global users:', error);
        res.status(500).json({ error: 'Erro ao buscar usuários globais.' });
    }
};

export const getGlobalOrganizations = async (req: Request, res: Response) => {
    try {
        const { data: organizations, error } = await supabase
            .from('organizations')
            .select('*');
        
        if (error && error.code !== '42P01') throw error;
        
        if (!organizations || organizations.length === 0) {
            return res.json([]);
        }
        
        const orgsWithMembers = await Promise.all(
            organizations.map(async (org) => {
                const { data: members } = await supabase
                    .from('user_organizations')
                    .select('*')
                    .eq('organization_id', org.id);
                    
                return {
                    ...org,
                    members: members || [],
                    memberCount: members?.length || 0
                };
            })
        );
        
        res.json(orgsWithMembers);
    } catch (error) {
        console.error('Error getting global organizations:', error);
        res.status(500).json({ error: 'Erro ao buscar organizações globais.' });
    }
};

export const toggleOrganizationBan = async (req: Request, res: Response) => {
    try {
        const { organizationId, isBanned } = req.body;

        if (!organizationId) {
            return res.status(400).json({ error: 'ID da organização é obrigatório.' });
        }

        const { data: org, error } = await supabase
            .from('organizations')
            .update({ is_banned: isBanned })
            .eq('id', organizationId)
            .select()
            .single();

        if (error) throw error;
        console.log(`Organization ${organizationId} ban status set to ${isBanned} by ${req.appUser?.email}`);
        res.json(org);
    } catch (error) {
        console.error('Error toggling organization ban:', error);
        res.status(500).json({ error: 'Erro ao atualizar status da organização.' });
    }
};