<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('attendance_devices')) {
            Schema::create('attendance_devices', function (Blueprint $table) {
                $table->id();
                $table->string('name');
                $table->string('serial_number')->unique();
                $table->string('location')->nullable();
                $table->boolean('is_active')->default(true);
                $table->timestamp('last_sync_at')->nullable();
                $table->timestamps();
            });
        }

        if (! Schema::hasTable('attendance_enrollments')) {
            Schema::create('attendance_enrollments', function (Blueprint $table) {
                $table->id();
                $table->foreignId('attendance_device_id')
                    ->constrained('attendance_devices')
                    ->cascadeOnDelete();
                $table->string('staff_type', 20);
                $table->unsignedBigInteger('staff_id');
                $table->string('device_user_id', 50);
                $table->timestamps();

                $table->unique(['attendance_device_id', 'device_user_id'], 'att_enroll_device_user_unique');
                $table->unique(['staff_type', 'staff_id', 'attendance_device_id'], 'att_enroll_staff_device_unique');
                $table->index(['staff_type', 'staff_id']);
            });
        }

        if (! Schema::hasTable('attendance_punches')) {
            Schema::create('attendance_punches', function (Blueprint $table) {
                $table->id();
                $table->foreignId('attendance_device_id')
                    ->nullable()
                    ->constrained('attendance_devices')
                    ->nullOnDelete();
                $table->foreignId('attendance_enrollment_id')
                    ->nullable()
                    ->constrained('attendance_enrollments')
                    ->nullOnDelete();
                $table->string('staff_type', 20);
                $table->unsignedBigInteger('staff_id');
                $table->timestamp('punched_at');
                $table->string('punch_type', 10);
                $table->string('source', 20)->default('device');
                $table->string('device_user_id', 50)->nullable();
                $table->timestamps();

                $table->index(['staff_type', 'staff_id', 'punched_at']);
                $table->index('punched_at');
            });
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('attendance_punches');
        Schema::dropIfExists('attendance_enrollments');
        Schema::dropIfExists('attendance_devices');
    }
};
