<?php

namespace Database\Seeders;

use App\Domains\Attachable\Models\Attachment;
use App\Domains\Attachable\Services\AttachmentService;
use App\Domains\Client\Models\Client;
use App\Domains\Tenant\Models\Tenant;
use App\Domains\Tenant\Services\TenantService;
use Illuminate\Database\Seeder;
use Illuminate\Http\UploadedFile;
use RuntimeException;
use Throwable;

class TenantSeeder extends Seeder
{
    private const ONTICKET_CLIENT_CODE = 'onticket';

    private const SONDER_CLIENT_CODE = 'sonder';

    private const SOCIAL_MEDIA = [
        [
            'code' => 'instagram',
            'url' => 'https://www.instagram.com/sonderargentina/',
            'orden' => 0,
        ],
        [
            'code' => 'facebook',
            'url' => 'https://www.facebook.com/SonderArgentina/',
            'orden' => 1,
        ],
        [
            'code' => 'linkedin',
            'url' => 'https://www.linkedin.com/company/35664983/',
            'orden' => 2,
        ],
        [
            'code' => 'whatsapp',
            'url' => 'https://wa.me/5493412602222',
            'orden' => 3,
        ],
    ];

    public function __construct(protected TenantService $tenantService) {}

    public function run(): void
    {
        $sonderClient = Client::query()->firstOrCreate(
            ['code' => self::SONDER_CLIENT_CODE],
            ['name' => 'Sonder'],
        );

        $onTicketClient = Client::query()->firstOrCreate(
            ['code' => self::ONTICKET_CLIENT_CODE],
            ['name' => 'OnTicket'],
        );

        $this->deleteTenant('sonder');

        Tenant::query()
            ->where('dominio', 'localhost')
            ->delete();

        $this->tenantService->create([
            'client_id' => $sonderClient->id,
            'codigo' => 'sonder',
            'nombre' => 'Sonder',
            'dominio' => 'localhost',
            'primary_color' => '#6376F3',
            'secondary_color' => '#A0A0A0',
            'danger_color' => '#FF8888',
            'success_color' => '#198754',
            'header_bg_color' => '#ffffff',
            'footer_bg_color' => '#313131',
            'display_categories' => true,
            'display_seach_bar' => true,
            'display_cart' => true,
            'cart_editing_policy' => 'quantity_and_remove',
            'checkout_editing_policy' => 'disabled',
            'header_logo' => $this->uploadedImage('images/tennants/sonder/sonder_header.png', 'sonder_header.png'),
            'footer_logo' => $this->uploadedImage('images/tennants/sonder/sonder_footer.png', 'sonder_footer.png'),
            'social_media' => self::SOCIAL_MEDIA,
            'website_type_code' => 'shopit',
            'extras' => [
                'carousel' => [
                    $this->uploadedImage(
                        'images/tennants/sonder/sonder-main-carousel/01-urban-team.png',
                        '01-urban-team.png',
                    ),
                    $this->uploadedImage(
                        'images/tennants/sonder/sonder-main-carousel/02-running-shoes.png',
                        '02-running-shoes.png',
                    ),
                    $this->uploadedImage(
                        'images/tennants/sonder/sonder-main-carousel/03-streetwear.png',
                        '03-streetwear.png',
                    ),
                    $this->uploadedImage(
                        'images/tennants/sonder/sonder-main-carousel/04-football-training.png',
                        '04-football-training.png',
                    ),
                    $this->uploadedImage(
                        'images/tennants/sonder/sonder-main-carousel/05-activewear-essentials.png',
                        '05-activewear-essentials.png',
                    ),
                    $this->uploadedImage(
                        'images/tennants/sonder/sonder-main-carousel/06-city-runners.png',
                        '06-city-runners.png',
                    ),
                ],
            ],
        ]);

        $this->deleteTenant('fiesta_futbol_infantil');

        $fiestaDomain = 'fiesta-futbol-infantil.localhost';
        Tenant::query()
            ->where('dominio', $fiestaDomain)
            ->delete();

        $this->tenantService->create([
            'client_id' => $onTicketClient->id,
            'codigo' => 'fiesta_futbol_infantil',
            'nombre' => 'Fiesta Fútbol Infantil',
            'dominio' => $fiestaDomain,
            'site_title' => 'Fiesta Fútbol Infantil',
            'primary_color' => '#00973F',
            'secondary_color' => '#A0A0A0',
            'danger_color' => '#FF8888',
            'success_color' => '#198754',
            'header_bg_color' => '#ffffff',
            'footer_bg_color' => '#015327',
            'display_categories' => false,
            'display_seach_bar' => false,
            'display_cart' => true,
            'cart_editing_policy' => 'full',
            'checkout_editing_policy' => 'disabled',
            'header_logo' => $this->uploadedImage(
                'images/tennants/fiesta_futbol_infantil/futbol_infantil_header.png',
                'futbol_infantil_header.png',
            ),
            'footer_logo' => $this->uploadedImage(
                'images/tennants/fiesta_futbol_infantil/futbol_infantil_footer.png',
                'futbol_infantil_footer.png',
            ),
            'favicon' => $this->uploadedImage(
                'images/tennants/fiesta_futbol_infantil/futbol_infantil_favicon.png',
                'futbol_infantil_favicon.png',
            ),
            'social_media' => self::SOCIAL_MEDIA,
            'website_type_code' => 'onticket',
            'extras' => [
                'heroConfig' => [
                    'title_html' => '<h1>Fiesta Fútbol Infantil</h1>',
                    'description_html' => '<p>Viví una jornada inolvidable de fútbol infantil.</p>',
                    'button_text' => 'Comprar entradas',
                    'button_href' => '/tickets',
                    'background_image_id' => $this->uploadedImage(
                        'images/tennants/fiesta_futbol_infantil/futbol_infantil_hero.png',
                        'futbol_infantil_hero.png',
                    ),
                ],
                'eventConfig' => [
                    'title' => 'Fiesta Fútbol Infantil',
                    'location' => 'Rosario, Santa Fe',
                    'dates_text' => '9, 10, 11 y 12 de Octubre 2026',
                    'dates' => [
                        [
                            'date' => '2026-12-05',
                            'start_time' => '09:00',
                            'end_time' => '18:00',
                        ],
                        [
                            'date' => '2026-12-06',
                            'start_time' => '09:00',
                            'end_time' => '18:00',
                        ],
                    ],
                ],
                'additionalInfoConfig' => [
                    'description' => <<<'HTML'
                        <div class="container-fluid px-0">
                            <div class="row g-4 text-start">
                                <div class="col-12 col-md-6">
                                    <ul class="mb-0 ps-3">
                                        <li class="mb-3">
                                            <strong>Menores y Accesos:</strong> Los niños menores de [X] años ingresan gratis acompañados por un adulto con entrada válida.
                                        </li>
                                        <li>
                                            <strong>Jugadores y Accesos:</strong> Los niños que participen del torneo ingresan según la acreditación otorgada a su club.
                                        </li>
                                    </ul>
                                </div>
                                <div class="col-12 col-md-6">
                                    <ul class="mb-0 ps-3">
                                        <li class="mb-3">
                                            <strong>Elementos prohibidos:</strong> No se permite el ingreso con pirotecnia, objetos cortantes, envases de vidrio ni bebidas alcohólicas.
                                        </li>
                                        <li>
                                            <strong>Entradas:</strong> No es necesario que imprimas tu entrada. Podés mostrar el código QR directamente desde tu celular. No tienen cambio ni devolución.
                                        </li>
                                    </ul>
                                </div>
                            </div>
                        </div>
                        HTML,
                ],
            ],
        ]);
    }

    private function deleteTenant(string $codigo): void
    {
        $tenant = Tenant::query()
            ->where('codigo', $codigo)
            ->first();

        if ($tenant === null) {
            return;
        }

        $attachmentService = app(AttachmentService::class);

        $extraAttachments = Attachment::query()
            ->where('path', 'like', 'tenants/%/extras/%')
            ->get()
            ->filter(
                fn (Attachment $attachment): bool => str_starts_with(
                    $attachment->path,
                    "tenants/{$codigo}/extras/"
                )
            );

        foreach ($extraAttachments as $attachment) {
            try {
                $attachmentService->delete($attachment);
            } catch (Throwable) {
                // Ignore cleanup errors while recreating demo data.
            }
        }

        if ($tenant->headerLogo) {
            try {
                $attachmentService->delete($tenant->headerLogo);
            } catch (Throwable) {
                // Ignore cleanup errors while recreating demo data.
            }
        }

        if ($tenant->footerLogo && $tenant->footer_logo_id !== $tenant->header_logo_id) {
            try {
                $attachmentService->delete($tenant->footerLogo);
            } catch (Throwable) {
                // Ignore cleanup errors while recreating demo data.
            }
        }

        if (
            $tenant->favicon
            && $tenant->favicon_id !== $tenant->header_logo_id
            && $tenant->favicon_id !== $tenant->footer_logo_id
        ) {
            try {
                $attachmentService->delete($tenant->favicon);
            } catch (Throwable) {
                // Ignore cleanup errors while recreating demo data.
            }
        }

        $tenant->delete();
    }

    private function uploadedImage(string $relativePath, string $filename): UploadedFile
    {
        $path = public_path($relativePath);

        if (! file_exists($path)) {
            throw new RuntimeException("Image not found at path: {$path}");
        }

        $mimeType = match (strtolower(pathinfo($filename, PATHINFO_EXTENSION))) {
            'jpg', 'jpeg' => 'image/jpeg',
            'gif' => 'image/gif',
            'webp' => 'image/webp',
            default => 'image/png',
        };

        return new UploadedFile(
            $path,
            $filename,
            $mimeType,
            null,
            true,
        );
    }
}
