import MatchService from '../services/matchService.js';
import fs from 'fs';

export const uploadCSV = async (req, res) => {
    try {
        const { clubId } = req.body;
        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: 'Failed to import CSV data' });
    }
};

export const getLeaguesForCurrentSeason = async (req, res) => {
    try {
        console.log(req.headers, req.params);
        const { authcode: userToken } = req.headers;
        const { clubId } = req.params;
        const leagues = await MatchService.getLeaguesForCurrentSeason(userToken, clubId);
        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 matches = await MatchService.getMatchesForLeagues(userToken, clubId);
        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 matches = await MatchService.getMatchesForLeague(userToken, clubId, leagueId);
        return res.status(200).json(matches);
    } catch (error) {
        console.error('Error retrieving matches:', error);
        return res.status(500).json({ error: 'Failed to retrieve matches' });
    }
};
