import {
  Entity,
  PrimaryGeneratedColumn,
  Column,
  CreateDateColumn,
  UpdateDateColumn,
  ManyToOne,
  JoinColumn,
  Index,
} from 'typeorm';
import { Student } from './student.entity';
import { Class } from './class.entity';
import { ClassSchedule } from './class-schedule.entity';
import { AttendanceSession } from './attendance-session.entity';

@Entity('attendance_records')
@Index(['classId', 'attendanceDate'])
@Index(['studentId', 'attendanceDate'])
@Index(['attendanceSessionId', 'studentId'], { unique: true })
export class AttendanceRecord {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ name: 'student_id', type: 'integer' })
  studentId: number;

  @ManyToOne(() => Student, { onDelete: 'CASCADE' })
  @JoinColumn({ name: 'student_id' })
  student: Student;

  @Column({ name: 'class_id', type: 'integer', nullable: true })
  classId: number;

  @ManyToOne(() => Class, { onDelete: 'SET NULL', nullable: true })
  @JoinColumn({ name: 'class_id' })
  class: Class;

  @Column({ name: 'schedule_id', type: 'integer', nullable: true })
  scheduleId: number | null;

  @ManyToOne(() => ClassSchedule, { onDelete: 'SET NULL', nullable: true })
  @JoinColumn({ name: 'schedule_id' })
  schedule: ClassSchedule | null;

  @Column({ name: 'attendance_session_id', type: 'integer', nullable: true })
  attendanceSessionId: number | null;

  @ManyToOne(() => AttendanceSession, (session) => session.records, {
    onDelete: 'SET NULL',
    nullable: true,
  })
  @JoinColumn({ name: 'attendance_session_id' })
  attendanceSession: AttendanceSession | null;

  @Column({ name: 'attendance_date', type: 'date' })
  attendanceDate: string;

  @Column({ length: 20 })
  session: string;

  @Column({ length: 20 })
  status: string;

  @Column({ type: 'varchar', length: 200, nullable: true })
  remark: string | null;

  @Column({ name: 'source', length: 20, default: 'manual' })
  source: string;

  @Column({ name: 'punch_time', type: 'datetime', nullable: true })
  punchTime: Date | null;

  @Column({ name: 'punch_source', type: 'varchar', length: 40, nullable: true })
  punchSource: string | null;

  @Column({ name: 'punch_device_name', type: 'varchar', length: 100, nullable: true })
  punchDeviceName: string | null;

  @Column({ name: 'punch_device_id', type: 'varchar', length: 100, nullable: true })
  punchDeviceId: string | null;

  @CreateDateColumn({ name: 'created_at' })
  createdAt: Date;

  @UpdateDateColumn({ name: 'updated_at' })
  updatedAt: Date;

}
