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

export enum AttendanceStatus {
  Present = "Present",
  Absent = "Absent",
  Leave = "Leave",
}

export interface IAttendance {
  id: number;
  employeeId: number;
  employeeName: string;
  status: AttendanceStatus;
  attendanceDate?: Date;
  isDeleted: boolean;
  createdAt?: Date;
  updatedAt?: Date;
}

interface IAttendanceCreationAttributes
  extends Optional<
    IAttendance,
    "id" | "createdAt" | "updatedAt" | "isDeleted" | "attendanceDate"
  > {}

class AttendanceModel
  extends Model<IAttendance, IAttendanceCreationAttributes>
  implements IAttendance
{
  public id!: number;
  public employeeId!: number;
  public employeeName!: string;
  public status!: AttendanceStatus;
  public attendanceDate?: Date;
  public isDeleted!: boolean;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

AttendanceModel.init(
  {
    id: { type: DataTypes.INTEGER, autoIncrement: true, primaryKey: true },
    employeeId: { type: DataTypes.INTEGER, allowNull: false },
    employeeName: { type: DataTypes.STRING, allowNull: false },
    status: {
      type: DataTypes.ENUM(...Object.values(AttendanceStatus)),
      allowNull: false,
      defaultValue: AttendanceStatus.Present,
    },
    attendanceDate: { type: DataTypes.DATE, allowNull: true },
    isDeleted: {
      type: DataTypes.BOOLEAN,
      allowNull: false,
      defaultValue: false,
    },
    createdAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
    updatedAt: {
      type: DataTypes.DATE,
      allowNull: false,
      defaultValue: DataTypes.NOW,
    },
  },
  {
    sequelize,
    tableName: "attendance",
  }
);

const attendanceValidationSchema = Joi.object({
  attendances: Joi.array()
    .items(
      Joi.object({
        employeeId: Joi.number().required(),
        employeeName: Joi.string().required(),
        status: Joi.string().required(),
        attendanceDate: Joi.date().iso().required(),
      })
    )
    .min(1)
    .required(),
});

export { AttendanceModel, attendanceValidationSchema };
