<?php

use App\Models\ProjectMosaic;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('project_mosaics', function (Blueprint $table) {
            $table->date('end_date')->nullable();
            $table->integer('offset')->default(7);
        });
        ProjectMosaic::all()->each(function (ProjectMosaic $project_mosaic) {
            $end_date = Carbon::parse(sprintf('%s-W%02d',$project_mosaic->year,$project_mosaic->week))->addDay(Carbon::THURSDAY);
            $project_mosaic->update(['end_date' => $end_date]);
        });
        Schema::table('project_mosaics', function (Blueprint $table) {
            $table->dropColumn('week');
            $table->dropColumn('year');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('project_mosaics', function (Blueprint $table) {
            // Add back year and week columns
            $table->integer('year');
            $table->integer('week');
        });

        // Extract year and week from end_date (assuming logic applied in up() is reversible)
        ProjectMosaic::all()->each(function (ProjectMosaic $project_mosaic) {
            if (!$project_mosaic->end_date) {
                return; // Skip if end_date is null
            }
            $project_mosaic->update(['year' => $project_mosaic->end_date->format('Y'), 'week' => $project_mosaic->end_date->format('W')]);
        });

        Schema::table('project_mosaics', function (Blueprint $table) {
            // Drop end_date and offset columns
            $table->dropColumn('end_date');
            $table->dropColumn('offset');
        });
    }

};
