<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('team_week_bonuses', function (Blueprint $table) {
            $table->id();
            $table->foreignId('team_id')->constrained()->cascadeOnDelete();
            $table->string('week_id', 16);
            $table->unsignedSmallInteger('mcm_bonus')->default(0);
            $table->unsignedSmallInteger('tyfcb_bonus')->default(0);
            $table->unsignedSmallInteger('attendance_bonus')->default(0);
            $table->timestamps();
            $table->unique(['team_id', 'week_id']);
        });

        // Backfill existing flat values into week 1.
        foreach (DB::table('teams')->get() as $team) {
            $mcm = (int) ($team->mcm_bonus ?? 0);
            $tyfcb = (int) ($team->tyfcb_bonus ?? 0);
            $att = (int) ($team->attendance_bonus ?? 0);
            if ($mcm === 0 && $tyfcb === 0 && $att === 0) continue;
            DB::table('team_week_bonuses')->insert([
                'team_id' => $team->id,
                'week_id' => 'w1',
                'mcm_bonus' => $mcm,
                'tyfcb_bonus' => $tyfcb,
                'attendance_bonus' => $att,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }

    public function down(): void
    {
        Schema::dropIfExists('team_week_bonuses');
    }
};
