import MatchService from '../services/matchService.js';
import fs from 'fs';
import { emitScheduleMatchUpdated } from '../services/socketService.js';
import { devLog } from '../utils/logger.js';
export const uploadCSV = async (req, res) => {
    try {
        const clubId = req.body?.clubId ?? req.query?.clubId;
        const { authcode: userToken} = req.headers;
        const filePath = req.file.path;
        const result = await MatchService.importCSV(userToken, clubId, filePath);
        fs.unlinkSync(filePath); // Delete the file after processing

        return res.status(200).json({
            message: 'CSV data successfully imported',
            data: result,
        });
    } catch (error) {
        console.error('Error importing CSV:', error);
        return res.status(500).json({
            error: error.message || 'Failed to import CSV data'
        });
    }
};

export const getLeaguesForCurrentSeason = async (req, res) => {
    try {
        devLog(req.headers, req.params);
        const { authcode: userToken } = req.headers;
        const { clubId } = req.params;
        const { seasonid: seasonId } = req.query;
        const leagues = await MatchService.getLeaguesForCurrentSeason(userToken, clubId, seasonId);
        return res.status(200).json(leagues);
    } catch (error) {
        console.error('Error retrieving leagues:', error);
        return res.status(500).json({ error: 'Failed to retrieve leagues' });
    }
};

export const getMatchesForLeagues = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { clubId } = req.params;
        const { seasonid: seasonId } = req.query;
        const matches = await MatchService.getMatchesForLeagues(userToken, clubId, seasonId);
        return res.status(200).json(matches);
    } catch (error) {
        console.error('Error retrieving matches:', error);
        return res.status(500).json({ error: 'Failed to retrieve matches' });
    }
};

export const getMatchesForLeague = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { clubId, leagueId } = req.params;
        const { scope = 'own' } = req.query;
        const matches = await MatchService.getMatchesForLeague(userToken, clubId, leagueId, scope);
        return res.status(200).json(matches);
    } catch (error) {
        console.error('Error retrieving matches:', error);
        return res.status(500).json({ error: 'Failed to retrieve matches' });
    }
};

export const getLeagueTable = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { clubId, leagueId } = req.params;
        const table = await MatchService.getLeagueTable(userToken, clubId, leagueId);
        return res.status(200).json(table);
    } catch (error) {
        console.error('Error retrieving league table:', error);
        return res.status(500).json({ error: 'Failed to retrieve league table' });
    }
};

export const fetchLeagueTableFromMyTischtennis = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { clubId, leagueId } = req.params;
        const { userid: userIdOrEmail } = req.headers;
        
        // Convert email to userId if needed
        let userId = userIdOrEmail;
        if (isNaN(userIdOrEmail)) {
            const User = (await import('../models/User.js')).default;
            const user = await User.findOne({ where: { email: userIdOrEmail } });
            if (!user) {
                return res.status(404).json({ error: 'User not found' });
            }
            userId = user.id;
        }
        
        const autoFetchService = (await import('../services/autoFetchMatchResultsService.js')).default;
        await autoFetchService.fetchAndUpdateLeagueTable(userId, leagueId);
        
        // Return updated table data
        const table = await MatchService.getLeagueTable(userToken, clubId, leagueId);
        return res.status(200).json({
            message: 'League table updated from MyTischtennis',
            data: table
        });
    } catch (error) {
        console.error('Error fetching league table from MyTischtennis:', error);
        return res.status(500).json({ error: 'Failed to fetch league table from MyTischtennis' });
    }
};

export const updateMatchPlayers = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { matchId } = req.params;
        const { playersReady, playersPlanned, playersPlayed } = req.body;
        
        const result = await MatchService.updateMatchPlayers(
            userToken,
            matchId,
            playersReady,
            playersPlanned,
            playersPlayed
        );

        if (result.clubId) {
            emitScheduleMatchUpdated(result.clubId, result.id, result.match || null);
        }

        return res.status(200).json({
            message: 'Match players updated successfully',
            data: result
        });
    } catch (error) {
        console.error('Error updating match players:', error);
        return res.status(error.statusCode || 500).json({ 
            error: error.message || 'Failed to update match players' 
        });
    }
};

export const getPlayerMatchStats = async (req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { clubId, leagueId } = req.params;
        const { seasonid: seasonId } = req.query;
        
        const stats = await MatchService.getPlayerMatchStats(userToken, clubId, leagueId, seasonId);
        
        return res.status(200).json(stats);
    } catch (error) {
        console.error('Error retrieving player match stats:', error);
        return res.status(error.statusCode || 500).json({ 
            error: error.message || 'Failed to retrieve player match stats' 
        });
    }
};

export const getMatchPlayers = async (req, res) => {
    try {
        const { clubId } = req.params;
        if (!clubId) {
            return res.status(400).json({ error: 'Club-ID fehlt' });
        }
        const Member = (await import('../models/Member.js')).default;
        const members = await Member.findAll({
            where: { clubId: clubId, active: true },
            attributes: ['id', 'firstName', 'lastName', 'gender']
        });
        return res.status(200).json(members);
    } catch (error) {
        console.error('Error retrieving match players:', error);
        return res.status(500).json({ error: 'Failed to retrieve match players' });
    }
};
