import { DataTypes } from 'sequelize';
import sequelize from '../database.js';
import Member from './Member.js';
import DiaryDate from './DiaryDates.js';
import Group from './Group.js';
import { encryptData, decryptData } from '../utils/encrypt.js';

const Participant = sequelize.define('Participant', {
    id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
        allowNull: false
    },
    diaryDateId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
            model: DiaryDate,
            key: 'id'
        }
    },
    memberId: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
            model: Member,
            key: 'id'
        }
    },
    attendanceStatus: {
        type: DataTypes.STRING(32),
        allowNull: false,
        defaultValue: 'present',
        validate: {
            isIn: [['present', 'excused', 'cancelled']]
        }
    },
    groupId: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: {
            model: Group,
            key: 'id'
        },
        onDelete: 'SET NULL',
        onUpdate: 'CASCADE'
    },
    notes: {
        type: DataTypes.STRING(4096),
        allowNull: true,
        set(value) {
            const encryptedValue = encryptData(value);
            this.setDataValue('notes', encryptedValue);
        },
        get() {
            try {
                const encryptedValue = this.getDataValue('notes');
                return encryptData ? decryptData(encryptedValue) : null;
            } catch (error) {
                return null;
            }
        }
    }
}, {
    underscored: true,
    tableName: 'participants',
    timestamps: true
});

export default Participant;
