import MemberService from "../services/memberService.js";
import MemberTransferService from "../services/memberTransferService.js";
import clickTtPlayerRegistrationService from "../services/clickTtPlayerRegistrationService.js";
import { emitMemberChanged } from '../services/socketService.js';

import { devLog } from '../utils/logger.js';
const getClubMembers = async(req, res) => {
    try {
        const { authcode: userToken } = req.headers;
        const { id: clubId } = req.params;
        const showAll = req.params.showAll ?? 'false';
        res.status(200).json(await MemberService.getClubMembers(userToken, clubId, showAll));
    } catch(error) {
        res.status(500).json({ error: 'systemerror' });
    }
}

const getWaitingApprovals = async(req, res) => {
    try {
        const { id: clubId } = req.params;
        const { authcode: userToken } = req.headers;
        const waitingApprovals = await MemberService.getApprovalRequests(userToken, clubId);
        res.status(200).json(waitingApprovals);
    } catch(error) {
        res.status(403).json({ error: error });
    }
} 

const setClubMembers = async (req, res) => {
    try {
    const { id: memberId, firstname: firstName, lastname: lastName, street, city, postalCode, birthdate, phone, email, active,
            testMembership, picsInInternetAllowed, gender, ttr, qttr, memberFormHandedOver, adultReleaseApproved, adultReserveApproved,
            contributionGroupCode, contacts } = req.body;
        const { id: clubId } = req.params;
        const { authcode: userToken } = req.headers;
        const addResult = await MemberService.setClubMember(userToken, clubId, memberId, firstName, lastName, street, city, postalCode, birthdate, 
            phone, email, active, testMembership, picsInInternetAllowed, gender, ttr, qttr, memberFormHandedOver, adultReleaseApproved, adultReserveApproved, contributionGroupCode, contacts);
        
        // Emit Socket-Event wenn Member erfolgreich erstellt/aktualisiert wurde
        if (addResult.status === 200) {
            emitMemberChanged(clubId);
        }
        
        res.status(addResult.status || 500).json(addResult.response);
    } catch (error) {
        console.error('[setClubMembers] - Error:', error);
        res.status(500).json({ error: 'Failed to save member' });
    }
}

const getMemberSepaMandate = async (req, res) => {
    try {
        const { clubId, memberId } = req.params;
        const { authcode: userToken } = req.headers;
        const result = await MemberService.getMemberSepaMandate(userToken, Number(clubId), Number(memberId));
        res.status(result.status || 500).json(result.response);
    } catch (error) {
        console.error('[getMemberSepaMandate] - Error:', error);
        res.status(500).json({ success: false, error: 'SEPA-Mandat konnte nicht geladen werden.' });
    }
};

const saveMemberSepaMandate = async (req, res) => {
    try {
        const { clubId, memberId } = req.params;
        const { authcode: userToken } = req.headers;
        const result = await MemberService.saveMemberSepaMandate(userToken, Number(clubId), Number(memberId), req.body || {});
        if (result.status === 200) {
            emitMemberChanged(clubId);
        }
        res.status(result.status || 500).json(result.response);
    } catch (error) {
        console.error('[saveMemberSepaMandate] - Error:', error);
        res.status(500).json({ success: false, error: 'SEPA-Mandat konnte nicht gespeichert werden.' });
    }
};

const getMemberPlayInterests = async (req, res) => {
    try {
        const { clubId } = req.params;
        const { seasonId, lineupHalf } = req.query;
        const { authcode: userToken } = req.headers;
        const result = await MemberService.getMemberPlayInterests(userToken, Number(clubId), Number(seasonId), String(lineupHalf || ''));
        res.status(result.status || 500).json(result.response);
    } catch (error) {
        console.error('[getMemberPlayInterests] - Error:', error);
        res.status(500).json({ error: 'Failed to load member play interests' });
    }
};

const setMemberPlayInterest = async (req, res) => {
    try {
        const { clubId } = req.params;
        const { memberId, seasonId, lineupHalf, interested = true } = req.body;
        const { authcode: userToken } = req.headers;
        const normalizedInterested = interested === true || interested === 'true' || interested === 1 || interested === '1';
        const result = await MemberService.setMemberPlayInterest(
            userToken,
            Number(clubId),
            Number(memberId),
            Number(seasonId),
            String(lineupHalf || ''),
            normalizedInterested
        );
        if (result.status === 200) {
            emitMemberChanged(clubId);
        }
        res.status(result.status || 500).json(result.response);
    } catch (error) {
        console.error('[setMemberPlayInterest] - Error:', error);
        res.status(500).json({ error: 'Failed to save member play interest' });
    }
};

const uploadMemberImage = async (req, res) => {
    try {
        const { clubId, memberId } = req.params;
        const { authcode: userToken } = req.headers;
        const makePrimary =
            req.body?.makePrimary === true ||
            req.body?.makePrimary === 'true' ||
            req.query?.makePrimary === 'true';
        const result = await MemberService.uploadMemberImage(userToken, clubId, memberId, req.file.buffer, { makePrimary });
        res.status(result.status).json(result.response ?? { success: false, error: 'Unknown upload result' });
    } catch (error) {
        console.error('[uploadMemberImage] - Error:', error);
        res.status(500).json({ error: 'Failed to upload image' });
    }
};

const getMemberImage = async (req, res) => {
    try {
        const { clubId, memberId, imageId } = req.params;
        const { authcode: userToken } = req.headers;
        // Support "latest" as imageId to get the latest image
        const actualImageId = imageId === 'latest' ? null : (imageId || null);
        const result = await MemberService.getMemberImage(userToken, clubId, memberId, actualImageId);
        if (result.status === 200) {
            res.sendFile(result.imagePath);
        } else {
            res.status(result.status).json({ error: result.error });
        }
    } catch (error) {
        console.error('[getMemberImage] - Error:', error);
        res.status(500).json({ error: 'Failed to retrieve image' });
    }
};

const updateRatingsFromMyTischtennis = async (req, res) => {
    try {
        const { id: clubId } = req.params;
        const { authcode: userToken } = req.headers;
        const result = await MemberService.updateRatingsFromMyTischtennis(userToken, clubId);
        res.status(result.status).json(result.response);
    } catch (error) {
        console.error('[updateRatingsFromMyTischtennis] - Error:', error);
        res.status(500).json({ error: 'Failed to update ratings' });
    }
};

const getMemberTtrHistory = async (req, res) => {
    try {
        const { clubId, memberId } = req.params;
        const { authcode: userToken } = req.headers;
        const result = await MemberService.getMemberTtrHistory(userToken, clubId, memberId);
        res.status(result.status).json(result.response);
    } catch (error) {
        console.error('[getMemberTtrHistory] - Error:', error);
        res.status(500).json({ success: false, error: 'TTR-Historie konnte nicht geladen werden.' });
    }
};

const refreshMemberTtrHistory = async (req, res) => {
    try {
        const { clubId, memberId } = req.params;
        const { authcode: userToken } = req.headers;
        const result = await MemberService.refreshMemberTtrHistory(userToken, clubId, memberId);
        res.status(result.status).json(result.response);
    } catch (error) {
        console.error('[refreshMemberTtrHistory] - Error:', error);
        res.status(500).json({ success: false, error: 'TTR-Historie konnte nicht aktualisiert werden.' });
    }
};

const rotateMemberImage = async (req, res) => {
    try {
        const { clubId, memberId, imageId } = req.params;
        const { direction } = req.body;
        const { authcode: userToken } = req.headers;
        
        if (!direction || !['left', 'right'].includes(direction)) {
            return res.status(400).json({ 
                success: false, 
                error: 'Ungültige Drehrichtung. Verwenden Sie "left" oder "right".' 
            });
        }
        
        const result = await MemberService.rotateMemberImage(userToken, clubId, memberId, imageId, direction);
        res.status(result.status).json(result.response);
    } catch (error) {
        console.error('[rotateMemberImage] - Error:', error);
        res.status(500).json({ success: false, error: 'Failed to rotate image' });
    }
};

const deleteMemberImage = async (req, res) => {
    try {
        const { clubId, memberId, imageId } = req.params;
        const { authcode: userToken } = req.headers;
        const result = await MemberService.deleteMemberImage(userToken, clubId, memberId, imageId);
        res.status(result.status).json(result.response);
    } catch (error) {
        console.error('[deleteMemberImage] - Error:', error);
        res.status(500).json({ success: false, error: 'Failed to delete image' });
    }
};

const generateMemberGallery = async (req, res) => {
    try {
        const { clubId } = req.params;
        const { authcode: userToken } = req.headers;
        const size = parseInt(req.query.size) || 200; // Default: 200x200
        const format = req.query.format || 'image'; // 'image' or 'json'
        
        // Bei format=json wird kein Bild erstellt, nur die Mitgliederliste zurückgegeben
        const createImage = format !== 'json';
        const result = await MemberService.generateMemberGallery(userToken, clubId, size, createImage);
        
        if (result.status === 200) {
            if (format === 'json') {
                // Return member information for interactive gallery (ohne Bild zu erstellen)
                return res.status(200).json({
                    members: result.galleryEntries.map(entry => ({
                        memberId: entry.memberId,
                        firstName: entry.firstName,
                        lastName: entry.lastName,
                        fullName: entry.fullName
                    }))
                });
            }
            res.setHeader('Content-Type', 'image/png');
            res.setHeader('Cache-Control', 'no-store');
            return res.status(200).send(result.buffer);
        }
        return res.status(result.status).json({ error: result.error || 'Galerie konnte nicht erstellt werden' });
    } catch (error) {
        console.error('[generateMemberGallery] - Error:', error);
        res.status(500).json({ error: 'Failed to generate member gallery' });
    }
};

const setPrimaryMemberImage = async (req, res) => {
    try {
        const { clubId, memberId, imageId } = req.params;
        const { authcode: userToken } = req.headers;
        const result = await MemberService.setPrimaryMemberImage(userToken, clubId, memberId, imageId);
        res.status(result.status).json(result.response);
    } catch (error) {
        console.error('[setPrimaryMemberImage] - Error:', error);
        res.status(500).json({ success: false, error: 'Failed to update primary image' });
    }
};

const quickUpdateTestMembership = async (req, res) => {
    try {
        const { clubId, memberId } = req.params;
        const { authcode: userToken } = req.headers;
        const result = await MemberService.quickUpdateTestMembership(userToken, clubId, memberId);
        res.status(result.status).json(result.response);
    } catch (error) {
        console.error('[quickUpdateTestMembership] - Error:', error);
        res.status(500).json({ error: 'Failed to update test membership' });
    }
};

const quickUpdateMemberFormHandedOver = async (req, res) => {
    try {
        const { clubId, memberId } = req.params;
        const { authcode: userToken } = req.headers;
        const result = await MemberService.quickUpdateMemberFormHandedOver(userToken, clubId, memberId);
        res.status(result.status).json(result.response);
    } catch (error) {
        console.error('[quickUpdateMemberFormHandedOver] - Error:', error);
        res.status(500).json({ error: 'Failed to update member form status' });
    }
};

const quickDeactivateMember = async (req, res) => {
    try {
        const { clubId, memberId } = req.params;
        const { authcode: userToken } = req.headers;
        const result = await MemberService.quickDeactivateMember(userToken, clubId, memberId);
        res.status(result.status).json(result.response);
    } catch (error) {
        console.error('[quickDeactivateMember] - Error:', error);
        res.status(500).json({ error: 'Failed to deactivate member' });
    }
};

const requestClickTtPlayerRegistration = async (req, res) => {
    try {
        const { clubId, memberId } = req.params;
        const { authcode: userToken } = req.headers;
        const userId = req.user?.id;
        const result = await clickTtPlayerRegistrationService.submitExistingPlayerApplication({
            userToken,
            userId,
            clubId,
            memberId
        });
        res.status(200).json(result);
    } catch (error) {
        console.error('[requestClickTtPlayerRegistration] - Error:', error);
        res.status(error.statusCode || error.status || 500).json({
            success: false,
            error: error.message || 'Click-TT-Antrag konnte nicht eingereicht werden',
            details: error.details || null
        });
    }
};

const transferMembers = async (req, res) => {
    try {
        const { id: clubId } = req.params;
        const { authcode: userToken } = req.headers;
        const config = req.body;

        // Validierung
        if (!config.transferEndpoint) {
            return res.status(400).json({ 
                success: false, 
                error: 'Übertragungs-Endpoint ist erforderlich' 
            });
        }

        if (!config.transferTemplate) {
            return res.status(400).json({ 
                success: false, 
                error: 'Übertragungs-Template ist erforderlich' 
            });
        }

        const result = await MemberTransferService.transferMembers(userToken, clubId, config);
        res.status(result.status).json(result.response);
    } catch (error) {
        console.error('[transferMembers] - Error:', error);
        res.status(500).json({ 
            success: false, 
            error: 'Fehler bei der Übertragung: ' + error.message 
        });
    }
};

export {
    getClubMembers,
    getWaitingApprovals,
    setClubMembers,
    getMemberSepaMandate,
    saveMemberSepaMandate,
    getMemberPlayInterests,
    setMemberPlayInterest,
    uploadMemberImage,
    getMemberImage,
    updateRatingsFromMyTischtennis,
    getMemberTtrHistory,
    refreshMemberTtrHistory,
    rotateMemberImage,
    transferMembers,
    quickUpdateTestMembership,
    quickUpdateMemberFormHandedOver,
    quickDeactivateMember,
    requestClickTtPlayerRegistration,
    deleteMemberImage,
    setPrimaryMemberImage,
    generateMemberGallery
};
