import { DataTypes, Model, Optional } from "sequelize";
import Joi from "joi";
import sequelize from "../middlewears/sequelize";
import { StudentModel } from "./student";
import { ClassModel } from "./class";

export interface ISession {
  id: number;
  name: string;
  classId: number;
  isDeleted: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}

interface ISessionAttributes
  extends Optional<ISession, "id" | "isDeleted" | "createdAt" | "updatedAt"> {}

class SessionModel
  extends Model<ISession, ISessionAttributes>
  implements ISession
{
  id!: number;
  name!: string;
  classId!: number;
  isDeleted!: boolean;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

SessionModel.init(
  {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    name: { type: DataTypes.STRING, allowNull: false },
    classId: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: { model: "classes", key: "id" },
    },
    isDeleted: {
      type: DataTypes.BOOLEAN,
      allowNull: true,
      defaultValue: false,
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
  },
  {
    sequelize,
    tableName: "sessions",
  }
);

const sessionValidationSchema = Joi.object({
  name: Joi.string().min(1).max(255).required(),
  classId: Joi.number().integer().required(),
  isDeleted: Joi.boolean().optional(),
});

const updateSessionValidationSchema = Joi.object({
  name: Joi.string().min(1).max(255).optional(),
  classId: Joi.number().integer().optional(),
  isDeleted: Joi.boolean().optional(),
});

// Associations are defined in associations.ts to avoid circular imports

export { SessionModel, sessionValidationSchema, updateSessionValidationSchema };
