import { DataTypes, type QueryInterface } from 'sequelize';

/**
 * Class-level daily attendance (WS-C). The teacher fills a per-class aggregate
 * that rolls up to campus → school → org. The owning class's campus/school/org
 * are denormalized onto the row so a tier rollup is a single-column SUM filter.
 * Idempotent.
 */
async function tableExists(
  queryInterface: QueryInterface,
  table: string,
): Promise<boolean> {
  const [results] = await queryInterface.sequelize.query(`
    SELECT 1 FROM information_schema.tables WHERE table_name = '${table}'
  `);
  return (results as unknown[]).length > 0;
}

export default {
  up: async (queryInterface: QueryInterface) => {
    if (!(await tableExists(queryInterface, 'class_attendance'))) {
      await queryInterface.createTable('class_attendance', {
        id: {
          type: DataTypes.UUID,
          defaultValue: DataTypes.UUIDV4,
          primaryKey: true,
        },
        classId: { type: DataTypes.UUID, allowNull: false },
        attendance_date: { type: DataTypes.DATEONLY, allowNull: false },
        total_enrolled: { type: DataTypes.INTEGER, allowNull: false },
        total_present: { type: DataTypes.INTEGER, allowNull: false },
        total_absent: { type: DataTypes.INTEGER, allowNull: false },
        total_tardy: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },
        attendance_percentage: { type: DataTypes.DECIMAL(5, 2), allowNull: true },
        recorded_by_label: { type: DataTypes.TEXT, allowNull: true },
        organizationId: { type: DataTypes.UUID, allowNull: true },
        schoolId: { type: DataTypes.UUID, allowNull: true },
        campusId: { type: DataTypes.UUID, allowNull: true },
        createdById: { type: DataTypes.UUID, allowNull: true },
        updatedById: { type: DataTypes.UUID, allowNull: true },
        createdAt: { type: DataTypes.DATE, allowNull: false },
        updatedAt: { type: DataTypes.DATE, allowNull: false },
        deletedAt: { type: DataTypes.DATE, allowNull: true },
      });
    }
  },

  down: async (queryInterface: QueryInterface) => {
    if (await tableExists(queryInterface, 'class_attendance')) {
      await queryInterface.dropTable('class_attendance');
    }
  },
};
