<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Step 1: Backfill - Link activities yang belum punya attendance_id
        // dengan attendance berdasarkan user_id + date
        DB::statement("
            UPDATE activities a
            INNER JOIN attendances att ON a.user_id = att.user_id 
                AND DATE(a.date) = DATE(att.date)
            SET a.attendance_id = att.id
            WHERE a.attendance_id IS NULL
        ");

        // Step 2: Delete activities yang tidak bisa di-link (orphan records)
        // Ini untuk data integrity - activities harus punya attendance
        DB::statement("
            DELETE FROM activities 
            WHERE attendance_id IS NULL
        ");

        // Step 3: Make attendance_id required
        Schema::table('activities', function (Blueprint $table) {
            $table->foreignId('attendance_id')
                ->nullable(false)
                ->change();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('activities', function (Blueprint $table) {
            $table->foreignId('attendance_id')
                ->nullable()
                ->change();
        });
    }
};
