import ClubTeamService from '../services/clubTeamService.js';
import { getUserByToken } from '../utils/userUtils.js';
import { devLog } from '../utils/logger.js';

export const getClubTeams = async (req, res) => {
    try {
        const { authcode: token } = req.headers;
        const { clubid: clubId } = req.params;
        const { seasonid: seasonId } = req.query;
        
        const user = await getUserByToken(token);
        
        // Check if user has access to this club
        const clubTeams = await ClubTeamService.getAllClubTeamsByClub(clubId, seasonId);
        
        res.status(200).json(clubTeams);
    } catch (error) {
        console.error('[getClubTeams] - Error:', error);
        res.status(500).json({ error: "internalerror" });
    }
};

export const getClubTeam = async (req, res) => {
    try {
        const { authcode: token } = req.headers;
        const { clubteamid: clubTeamId } = req.params;
        const user = await getUserByToken(token);
        
        const clubTeam = await ClubTeamService.getClubTeamById(clubTeamId);
        if (!clubTeam) {
            return res.status(404).json({ error: "notfound" });
        }
        
        res.status(200).json(clubTeam);
    } catch (error) {
        console.error('[getClubTeam] - Error:', error);
        res.status(500).json({ error: "internalerror" });
    }
};

export const createClubTeam = async (req, res) => {
    try {
        const { authcode: token } = req.headers;
        const { clubid: clubId } = req.params;
        const { name, leagueId, seasonId, teamGender, teamAgeGroup, plannedLeagueName } = req.body;
        
        const user = await getUserByToken(token);
        
        if (!name) {
            return res.status(400).json({ error: "missingname" });
        }
        
        const planned = plannedLeagueName !== undefined && plannedLeagueName !== null
            ? String(plannedLeagueName).trim() || null
            : undefined;
        const clubTeamData = {
            name,
            clubId: parseInt(clubId),
            leagueId: leagueId ? parseInt(leagueId) : null,
            seasonId: seasonId ? parseInt(seasonId) : null,
            teamGender: teamGender || 'open',
            teamAgeGroup: teamAgeGroup || 'adult',
            ...(planned !== undefined ? { plannedLeagueName: planned } : {})
        };
        
        const newClubTeam = await ClubTeamService.createClubTeam(clubTeamData);
        
        res.status(201).json(newClubTeam);
    } catch (error) {
        console.error('[createClubTeam] - Error:', error);
        res.status(500).json({ error: "internalerror" });
    }
};

export const updateClubTeam = async (req, res) => {
    try {
        const { authcode: token } = req.headers;
        const { clubteamid: clubTeamId } = req.params;
        const { name, leagueId, seasonId, teamGender, teamAgeGroup, plannedLeagueName } = req.body;
        
        const user = await getUserByToken(token);
        
        const updateData = {};
        if (name !== undefined) updateData.name = name;
        if (leagueId !== undefined) updateData.leagueId = leagueId ? parseInt(leagueId) : null;
        if (seasonId !== undefined) updateData.seasonId = seasonId ? parseInt(seasonId) : null;
        if (teamGender !== undefined) updateData.teamGender = teamGender || 'open';
        if (teamAgeGroup !== undefined) updateData.teamAgeGroup = teamAgeGroup || 'adult';
        if (plannedLeagueName !== undefined) {
            updateData.plannedLeagueName = plannedLeagueName === null || plannedLeagueName === ''
                ? null
                : String(plannedLeagueName).trim() || null;
        }
        
        const success = await ClubTeamService.updateClubTeam(clubTeamId, updateData);
        if (!success) {
            return res.status(404).json({ error: "notfound" });
        }
        
        const updatedClubTeam = await ClubTeamService.getClubTeamById(clubTeamId);
        res.status(200).json(updatedClubTeam);
    } catch (error) {
        console.error('[updateClubTeam] - Error:', error);
        res.status(500).json({ error: "internalerror" });
    }
};

export const deleteClubTeam = async (req, res) => {
    try {
        const { authcode: token } = req.headers;
        const { clubteamid: clubTeamId } = req.params;
        const user = await getUserByToken(token);
        
        const success = await ClubTeamService.deleteClubTeam(clubTeamId);
        if (!success) {
            return res.status(404).json({ error: "notfound" });
        }
        
        res.status(200).json({ message: "Club team deleted successfully" });
    } catch (error) {
        console.error('[deleteClubTeam] - Error:', error);
        res.status(500).json({ error: "internalerror" });
    }
};

export const getLeagues = async (req, res) => {
    try {
        const { authcode: token } = req.headers;
        const { clubid: clubId } = req.params;
        const { seasonid: seasonId } = req.query;
        
        const user = await getUserByToken(token);
        
        const leagues = await ClubTeamService.getLeaguesByClub(clubId, seasonId);
        
        res.status(200).json(leagues);
    } catch (error) {
        console.error('[getLeagues] - Error:', error);
        res.status(500).json({ error: "internalerror" });
    }
};

export const getClubTeamLineup = async (req, res) => {
    try {
        const { authcode: token } = req.headers;
        const { clubteamid: clubTeamId } = req.params;
        const lineupHalf = req.query.half === 'second_half' ? 'second_half' : 'first_half';
        await getUserByToken(token);

        const clubTeam = await ClubTeamService.getClubTeamById(clubTeamId);
        if (!clubTeam) {
            return res.status(404).json({ error: "notfound" });
        }

        const lineup = await ClubTeamService.getTeamLineup(clubTeamId, lineupHalf);
        res.status(200).json(lineup);
    } catch (error) {
        console.error('[getClubTeamLineup] - Error:', error);
        res.status(500).json({ error: "internalerror" });
    }
};

export const updateClubTeamLineup = async (req, res) => {
    try {
        const { authcode: token } = req.headers;
        const { clubteamid: clubTeamId } = req.params;
        const { assignments, lineupHalf: requestLineupHalf } = req.body;
        const lineupHalf = requestLineupHalf === 'second_half' || req.query.half === 'second_half' ? 'second_half' : 'first_half';
        await getUserByToken(token);

        const clubTeam = await ClubTeamService.getClubTeamById(clubTeamId);
        if (!clubTeam) {
            return res.status(404).json({ error: "notfound" });
        }

        const lineup = await ClubTeamService.replaceTeamLineup(clubTeamId, assignments, lineupHalf);
        res.status(200).json(lineup);
    } catch (error) {
        console.error('[updateClubTeamLineup] - Error:', error);
        if (error?.code === 'TEAM_LINEUP_TABLE_MISSING') {
            return res.status(500).json({ error: 'teamlineuptablemissing' });
        }
        res.status(500).json({ error: "internalerror" });
    }
};
