import Accident from '../models/Accident.js';
import DiaryDate from '../models/DiaryDates.js';
import Member from '../models/Member.js';
import { checkAccess, getUserByToken} from '../utils/userUtils.js';

import { devLog } from '../utils/logger.js';
class AccidentService {
    async createAccident(userToken, clubId, memberId, diaryDateId, accident) {
        await checkAccess(userToken, clubId);
        const user = await getUserByToken(userToken);
        if (!user) {
            throw new Error('User not found'); 
        }
        const member = await Member.findByPk(memberId);
        if (!member || member.clubId != clubId) {
            throw new Error('Member not found');
        }
        devLog(diaryDateId);
        const diaryDate = await DiaryDate.findByPk(diaryDateId);
        if (!diaryDate || diaryDate.clubId != clubId) {
            throw new Error('Diary date not found');
        }
        const newAccident = await Accident.create({
            memberId,
            diaryDateId: diaryDate.id,
            accident,
        });

        return newAccident; 
    }

    async getAccidents(userToken, clubId, diaryDateId) {
        await checkAccess(userToken, clubId);
        const user = await getUserByToken(userToken);
        if (!user) {
            throw new Error('User not found');
        }
        const diaryDate = await DiaryDate.findByPk(diaryDateId);
        if (!diaryDate || diaryDate.clubId != clubId) {
            throw new Error('Diary date not found');
        }
        const accidents = await Accident.findAll({
            where: {
                diaryDateId,
            },
            include: [{
                model: Member,
                as: 'members'
            }]
        });
        const cleanupedAccidents = accidents.map(accident => {
            return {
                accident: accident.accident,
                firstName: accident.members.firstName,
                lastName: accident.members.lastName,
            }
        })
        return cleanupedAccidents;
    }
}

export default new AccidentService();
