<?php

use App\Models\Lubricante;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    private const THUMBNAIL_QUALITY = 90;

    /**
     * Registra los tamaños de imagen del catálogo de lubricantes durante la
     * migración para que el feature funcione igual en ambientes nuevos y CI.
     */
    public function up(): void
    {
        $now = now();

        DB::table('image_settings')->updateOrInsert(
            [
                'type' => Lubricante::class,
                'key' => null,
            ],
            [
                'upload_to' => Lubricante::IMAGE_UPLOAD_TO,
                'active' => true,
                'created_at' => $now,
                'updated_at' => $now,
            ]
        );

        $settings = DB::table('image_settings')
            ->select(['id'])
            ->where('type', Lubricante::class)
            ->whereNull('key')
            ->first();

        if (!$settings) {
            return;
        }

        $thumbnails = [
            ['size' => Lubricante::IMAGE_SIZE_SMALL, 'width' => 196, 'height' => 112, 'order_no' => 1],
            ['size' => Lubricante::IMAGE_SIZE_MEDIUM, 'width' => 393, 'height' => 224, 'order_no' => 2],
            ['size' => Lubricante::IMAGE_SIZE_LARGE, 'width' => 786, 'height' => 448, 'order_no' => 3],
        ];

        foreach ($thumbnails as $thumbnail) {
            DB::table('thumbnail_settings')->updateOrInsert(
                [
                    'image_settings_id' => $settings->id,
                    'size' => $thumbnail['size'],
                ],
                [
                    'width' => $thumbnail['width'],
                    'height' => $thumbnail['height'],
                    'cropped' => true,
                    'quality' => self::THUMBNAIL_QUALITY,
                    'order_no' => $thumbnail['order_no'],
                    'active' => true,
                    'updated_at' => $now,
                    'created_at' => $now,
                ]
            );
        }
    }

    public function down(): void
    {
        $settings = DB::table('image_settings')
            ->select(['id'])
            ->where('type', Lubricante::class)
            ->whereNull('key')
            ->first();

        if (!$settings) {
            return;
        }

        DB::table('thumbnail_settings')
            ->where('image_settings_id', $settings->id)
            ->delete();

        DB::table('image_settings')
            ->where('id', $settings->id)
            ->delete();
    }
};
