import UserClub from "../models/UserClub.js";
import { checkAccess } from "../utils/userUtils.js";
import { getUserByToken } from "../utils/userUtils.js";
import Member from "../models/Member.js";
import path from 'path';
import fs from 'fs';
import sharp from 'sharp';

class MemberService {
    async getApprovalRequests(userToken, clubId) {
        console.log('[MemberService::getApprovalRequest] - Check user access');
        await checkAccess(userToken, clubId);
        console.log('[MemberService::getApprovalRequest] - Load user');
        const user = await getUserByToken(userToken);
        console.log('[MemberService::getApprovalRequest] - Load userclub');
        return await UserClub.findAll({
            where: {
                clubId: clubId,
                approved: false,
                userId: user.id 
            }
        }); 
    }

    async getClubMembers(userToken, clubId, showAll) {
        console.log('[getClubMembers] - Check access');
        await checkAccess(userToken, clubId);
        console.log('[getClubMembers] - Find members');
        const where = {
            clubId: clubId
        };
        if (!showAll || showAll === 'false') {
            where['active'] = true;
        }
        return await Member.findAll({ where })
            .then(members => {
                return members.map(member => {
                    const imagePath = path.join('images', 'members', `${member.id}.jpg`);
                    const hasImage = fs.existsSync(imagePath);
                    return {
                        ...member.toJSON(),
                        hasImage: hasImage
                    };
                });
            })
            .then(membersWithImageStatus => {
                console.log('[getClubMembers] - return members');
                return membersWithImageStatus;
            })
            .catch(error => {
                console.error('[getClubMembers] - Error:', error);
                throw error;
            });
    }

    async setClubMember(userToken, clubId, memberId, firstName, lastName, street, city, birthdate, phone, email, active = true, testMembership = false,
        picsInInternetAllowed = false) {
        try {
            console.log('[setClubMembers] - Check access');
            await checkAccess(userToken, clubId);
            console.log('[setClubMembers] - set default member');
            let member = null;
            console.log('[setClubMembers] - load member if possible');
            if (memberId) {
                member = await Member.findOne({ where: { id: memberId } });
            }
            console.log('[setClubMembers] - set member');
            if (member) {
                member.firstName = firstName;
                member.lastName = lastName;
                member.street = street;
                member.city = city;
                member.birthDate = birthdate;
                member.phone = phone;
                member.email = email;
                member.active = active; 
                member.testMembership = testMembership;
                member.picsInInternetAllowed = picsInInternetAllowed;
                await member.save();
            } else {
                await Member.create({
                    firstName: firstName,
                    lastName: lastName,
                    street: street,
                    city: city,
                    birthDate: birthdate,
                    phone: phone,
                    email: email,
                    clubId: clubId,
                    active: active,
                    testMembership: testMembership,
                    picsInInternetAllowed: picsInInternetAllowed,
                });
            }
            console.log('[setClubMembers] - return response');
            return {
                status: 200,
                response: { result: "success" },
            }
        } catch (error) {
            console.log(error);
            return {
                status: error.statusCode || 500,
                response: { error: "nocreation" }
            }
        }
    }

    async uploadMemberImage(userToken, clubId, memberId, imageBuffer) {
        try {
            console.log('------>', userToken, clubId, memberId, imageBuffer);
            await checkAccess(userToken, clubId);
            const member = await Member.findOne({ where: { id: memberId, clubId: clubId } });
            if (!member) {
                return { status: 404, error: 'Member not found in this club' };
            }
            const imagePath = path.join('images', 'members', `${memberId}.jpg`);
            await sharp(imageBuffer)
                .resize(600, 600)
                .jpeg({ quality: 80 })
                .toFile(imagePath);

            return { status: 200, message: 'Image uploaded successfully' };
        } catch (error) {
            console.error('[uploadMemberImage] - Error:', error);
            return { status: 500, error: 'Failed to upload image' };
        }
    }

    async getMemberImage(userToken, clubId, memberId) {
        try {
            await checkAccess(userToken, clubId);
            const member = await Member.findOne({ where: { id: memberId, clubId: clubId } });
            if (!member) {
                return { status: 404, error: 'Member not found in this club' };
            }
            const imagePath = path.join('images', 'members', `${memberId}.jpg`);
            if (!fs.existsSync(imagePath)) {
                return { status: 404, error: 'Image not found' };
            }
            return { status: 200, imagePath: path.resolve(imagePath) };
        } catch (error) {
            console.error('[getMemberImage] - Error:', error);
            return { status: 500, error: 'Failed to retrieve image' };
        }
    }
}

export default new MemberService();