<?php

namespace Database\Seeders;

use App\Models\Media;
use App\Models\MediaUsage;
use App\Models\Service;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\File;

class MediaSeeder extends Seeder
{
    public function run(): void
    {
        $this->purgeDeprecatedServiceAssets();

        $assets = [
            [
                'source' => 'public/uploads/logos/saleem-sial-logo.png',
                'destination' => 'uploads/system/saleem-sial-logo.png',
                'name' => 'Saleem Sial Logo PNG',
                'type' => 'image',
                'category' => 'branding',
                'alt_text' => 'Saleem Sial Analytics logo',
            ],
            [
                'source' => 'public/uploads/logos/saleem-sial-logo.jpeg',
                'destination' => 'uploads/system/saleem-sial-logo.jpeg',
                'name' => 'Saleem Sial Logo',
                'type' => 'image',
                'category' => 'branding',
                'alt_text' => 'Saleem Sial Analytics logo',
            ],
            [
                'source' => 'public/uploads/placeholders/saleem-sial-favicon.png',
                'destination' => 'uploads/system/saleem-sial-favicon.png',
                'name' => 'Saleem Sial Favicon',
                'type' => 'image',
                'category' => 'branding',
                'alt_text' => 'Saleem Sial Analytics favicon',
            ],
            [
                'source' => 'public/uploads/placeholders/default-favicon.ico',
                'destination' => 'uploads/system/default-favicon.ico',
                'name' => 'Default Favicon',
                'type' => 'image',
                'category' => 'branding',
                'alt_text' => 'Saleem Sial Analytics favicon',
            ],
            [
                'source' => null,
                'destination' => 'uploads/system/hero-analytics-dashboard.svg',
                'name' => 'Analytics Dashboard Hero',
                'type' => 'image',
                'category' => 'hero',
                'alt_text' => 'Illustrated analytics dashboard preview',
                'inline' => $this->heroSvg(),
            ],
            ...$this->serviceUploadAssets(),
            ...$this->trustedAssets(),
            ...$this->featureAssets(),
            ...$this->benefitAssets(),
            ...$this->caseStudyAssets(),
        ];

        foreach ($assets as $index => $asset) {
            $this->ensureAssetExists($asset);

            $path = $asset['destination'];
            $absolutePath = storage_path('app/public/' . $path);

            if (! File::exists($absolutePath)) {
                continue;
            }

            $mimeType = File::mimeType($absolutePath) ?: 'application/octet-stream';
            $imageSize = @getimagesize($absolutePath) ?: [null, null];

            Media::updateOrCreate(
                ['file_path' => $path],
                [
                    'name' => $asset['name'],
                    'disk' => 'public',
                    'type' => $asset['type'],
                    'mime_type' => $mimeType,
                    'extension' => strtolower((string) pathinfo($absolutePath, PATHINFO_EXTENSION)),
                    'size' => File::size($absolutePath),
                    'width' => $imageSize[0],
                    'height' => $imageSize[1],
                    'category' => $asset['category'],
                    'is_system' => $asset['is_system'] ?? true,
                    'alt_text' => $asset['alt_text'],
                    'sort_order' => $index,
                ]
            );
        }
    }

    protected function ensureAssetExists(array $asset): void
    {
        $destination = storage_path('app/public/' . $asset['destination']);
        File::ensureDirectoryExists(dirname($destination));

        if (isset($asset['inline'])) {
            File::put($destination, $asset['inline']);

            return;
        }

        if (blank($asset['source'] ?? null)) {
            return;
        }

        $source = base_path($asset['source']);

        if (! File::exists($source)) {
            return;
        }

        File::copy($source, $destination);
    }

    protected function serviceUploadAssets(): array
    {
        return [
            [
                'source' => null,
                'destination' => 'uploads/media/2jfV7sDvnzxNqDruKT45yev8aeQvMHLXHQoowUtM.webp',
                'name' => 'GA4 Service Image',
                'type' => 'image',
                'category' => 'service-image',
                'alt_text' => 'GA4 service image',
                'is_system' => false,
            ],
            [
                'source' => null,
                'destination' => 'uploads/media/v79FaD7gAYHhwhCVU9jXaW6Wyo19v4wpO9OFcmuQ.png',
                'name' => 'GA4 Service Icon',
                'type' => 'image',
                'category' => 'service-icon',
                'alt_text' => 'GA4 service icon',
                'is_system' => false,
            ],
            [
                'source' => null,
                'destination' => 'uploads/media/6CjrhLevKyKTEg5X52DUr8LRDdQJESmjFCnueG4W.png',
                'name' => 'GTM Service Image',
                'type' => 'image',
                'category' => 'service-image',
                'alt_text' => 'GTM service image',
                'is_system' => false,
            ],
            [
                'source' => null,
                'destination' => 'uploads/media/kiMpmVYtvcfuAtyLh02wRHiwsu2vLmTiV6kQpQYl.jpg',
                'name' => 'GTM Service Icon',
                'type' => 'image',
                'category' => 'service-icon',
                'alt_text' => 'GTM service icon',
                'is_system' => false,
            ],
            [
                'source' => null,
                'destination' => 'uploads/media/UVIb8sZBOy3DJRF4pYk5rO19RyPe1albJ1xEojni.png',
                'name' => 'Looker Studio Service Image',
                'type' => 'image',
                'category' => 'service-image',
                'alt_text' => 'Looker Studio service image',
                'is_system' => false,
            ],
            [
                'source' => null,
                'destination' => 'uploads/media/Y4Bi7JUJUcsDY20kUyTIBtVMZKoSRUljI2g5AXoN.png',
                'name' => 'Looker Studio Service Icon',
                'type' => 'image',
                'category' => 'service-icon',
                'alt_text' => 'Looker Studio service icon',
                'is_system' => false,
            ],
            [
                'source' => null,
                'destination' => 'uploads/media/nx7tqNOE2Md4WPPJZzuLLohQRmPxaaniDb6oBPRQ.png',
                'name' => 'Google Ads Service Image',
                'type' => 'image',
                'category' => 'service-image',
                'alt_text' => 'Google Ads service image',
                'is_system' => false,
            ],
            [
                'source' => null,
                'destination' => 'uploads/media/s9G0trlaaAP9twGJP9LWkGaxLMNoMgl0uLnchQ7q.png',
                'name' => 'Google Ads Service Icon',
                'type' => 'image',
                'category' => 'service-icon',
                'alt_text' => 'Google Ads service icon',
                'is_system' => false,
            ],
            [
                'source' => null,
                'destination' => 'uploads/media/oLV2M4zm3xkLMAJw2XHglJ2xs4Ejcm8II8smXSrb.png',
                'name' => 'Meta Ads Service Image',
                'type' => 'image',
                'category' => 'service-image',
                'alt_text' => 'Meta Ads service image',
                'is_system' => false,
            ],
            [
                'source' => null,
                'destination' => 'uploads/media/HcPhcJm39jfEcKKBzswosdyEpf1uoIXLTLXBaqW5.png',
                'name' => 'Meta Ads Service Icon',
                'type' => 'image',
                'category' => 'service-icon',
                'alt_text' => 'Meta Ads service icon',
                'is_system' => false,
            ],
            [
                'source' => null,
                'destination' => 'uploads/media/j7cTcFcX5wqiMhsfhk4lBuGGEHKs1Qo4M6qMqcmW.png',
                'name' => 'TikTok Ads Service Image',
                'type' => 'image',
                'category' => 'service-image',
                'alt_text' => 'TikTok Ads service image',
                'is_system' => false,
            ],
            [
                'source' => null,
                'destination' => 'uploads/media/zYN1PnqHn8r1OPnyHYMS29Xvw8xqA9V1BdRG7NqK.png',
                'name' => 'TikTok Ads Service Icon',
                'type' => 'image',
                'category' => 'service-icon',
                'alt_text' => 'TikTok Ads service icon',
                'is_system' => false,
            ],
            [
                'source' => null,
                'destination' => 'uploads/media/e8bTxQAhm5KtudWpwVuUuQzV7jt6ethzBLHghSuU.png',
                'name' => 'Server Side Tracking Service Image',
                'type' => 'image',
                'category' => 'service-image',
                'alt_text' => 'Server side tracking service image',
                'is_system' => false,
            ],
            [
                'source' => null,
                'destination' => 'uploads/media/iJcm5ue8eXcbASnWFv0OMQgo4xkilmSfM3vT7Gd8.png',
                'name' => 'Server Side Tracking Service Icon',
                'type' => 'image',
                'category' => 'service-icon',
                'alt_text' => 'Server side tracking service icon',
                'is_system' => false,
            ],
        ];
    }

    protected function purgeDeprecatedServiceAssets(): void
    {
        foreach ($this->deprecatedServiceAssetMap() as $duplicatePath => $originalPath) {
            $duplicate = Media::query()->where('file_path', $duplicatePath)->first();

            $this->deleteStoredFile($duplicatePath);

            if (! $duplicate) {
                continue;
            }

            $originalId = Media::query()->where('file_path', $originalPath)->value('id');

            if ($duplicate->category === 'service-image') {
                Service::query()
                    ->where('image_media_id', $duplicate->id)
                    ->update(['image_media_id' => $originalId]);
            }

            if ($duplicate->category === 'service-icon') {
                Service::query()
                    ->where('icon_media_id', $duplicate->id)
                    ->update(['icon_media_id' => $originalId]);
            }

            MediaUsage::query()->where('media_id', $duplicate->id)->delete();
            $duplicate->delete();
        }
    }

    protected function deprecatedServiceAssetMap(): array
    {
        return [
            'uploads/system/ga4.jpg' => 'uploads/media/2jfV7sDvnzxNqDruKT45yev8aeQvMHLXHQoowUtM.webp',
            'uploads/system/ga4-icon.png' => 'uploads/media/v79FaD7gAYHhwhCVU9jXaW6Wyo19v4wpO9OFcmuQ.png',
            'uploads/system/gtm.jpg' => 'uploads/media/6CjrhLevKyKTEg5X52DUr8LRDdQJESmjFCnueG4W.png',
            'uploads/system/gtm-icon.png' => 'uploads/media/kiMpmVYtvcfuAtyLh02wRHiwsu2vLmTiV6kQpQYl.jpg',
            'uploads/system/looker.jpg' => 'uploads/media/UVIb8sZBOy3DJRF4pYk5rO19RyPe1albJ1xEojni.png',
            'uploads/system/looker-icon.png' => 'uploads/media/Y4Bi7JUJUcsDY20kUyTIBtVMZKoSRUljI2g5AXoN.png',
            'uploads/system/google-ads.jpg' => 'uploads/media/nx7tqNOE2Md4WPPJZzuLLohQRmPxaaniDb6oBPRQ.png',
            'uploads/system/google-ads-icon.png' => 'uploads/media/s9G0trlaaAP9twGJP9LWkGaxLMNoMgl0uLnchQ7q.png',
            'uploads/system/meta.jpg' => 'uploads/media/oLV2M4zm3xkLMAJw2XHglJ2xs4Ejcm8II8smXSrb.png',
            'uploads/system/meta-icon.png' => 'uploads/media/HcPhcJm39jfEcKKBzswosdyEpf1uoIXLTLXBaqW5.png',
            'uploads/system/tiktok.jpg' => 'uploads/media/j7cTcFcX5wqiMhsfhk4lBuGGEHKs1Qo4M6qMqcmW.png',
            'uploads/system/tiktok-icon.png' => 'uploads/media/zYN1PnqHn8r1OPnyHYMS29Xvw8xqA9V1BdRG7NqK.png',
            'uploads/system/server-side.jpg' => 'uploads/media/e8bTxQAhm5KtudWpwVuUuQzV7jt6ethzBLHghSuU.png',
            'uploads/system/server-side-icon.png' => 'uploads/media/iJcm5ue8eXcbASnWFv0OMQgo4xkilmSfM3vT7Gd8.png',
        ];
    }

    protected function deleteStoredFile(string $path): void
    {
        $absolutePath = storage_path('app/public/' . $path);

        if (File::exists($absolutePath)) {
            File::delete($absolutePath);
        }
    }

    protected function trustedAssets(): array
    {
        $assets = [];

        for ($index = 0; $index < 5; $index++) {
            $suffix = $index === 0 ? '' : '-' . $index;
            $assets[] = [
                'source' => 'public/assets/themes/prespa-saas/assets/img/ps-patterns/partners/Container' . $suffix . '.png',
                'destination' => 'uploads/system/trusted-' . ($index + 1) . '.png',
                'name' => 'Trusted Logo ' . ($index + 1),
                'type' => 'image',
                'category' => 'trusted-logo',
                'alt_text' => 'Trusted partner logo ' . ($index + 1),
            ];
        }

        return $assets;
    }

    protected function featureAssets(): array
    {
        return [
            [
                'source' => 'public/assets/themes/prespa-saas/assets/img/ps-patterns/pillars/TrendingIcon-cropped.png',
                'destination' => 'uploads/system/why-tracking-trending.png',
                'name' => 'Why Tracking Trend Icon',
                'type' => 'image',
                'category' => 'feature-icon',
                'alt_text' => 'Trend icon',
            ],
            [
                'source' => 'public/assets/themes/prespa-saas/assets/img/ps-patterns/pillars/CloudIcon-cropped.png',
                'destination' => 'uploads/system/why-tracking-cloud.png',
                'name' => 'Why Tracking Cloud Icon',
                'type' => 'image',
                'category' => 'feature-icon',
                'alt_text' => 'Cloud icon',
            ],
            [
                'source' => 'public/assets/themes/prespa-saas/assets/img/ps-patterns/pillars/TaskIcon-cropped.png',
                'destination' => 'uploads/system/why-tracking-task.png',
                'name' => 'Why Tracking Task Icon',
                'type' => 'image',
                'category' => 'feature-icon',
                'alt_text' => 'Task icon',
            ],
            [
                'source' => 'public/assets/themes/prespa-saas/assets/img/ps-patterns/pillars/Speedometer-cropped.png',
                'destination' => 'uploads/system/why-tracking-speedometer.png',
                'name' => 'Why Tracking Speedometer Icon',
                'type' => 'image',
                'category' => 'feature-icon',
                'alt_text' => 'Speedometer icon',
            ],
        ];
    }

    protected function benefitAssets(): array
    {
        $files = [
            'bar-chart',
            'pie-chart',
            'sparkles',
            'workflows',
            'file',
            'circles',
        ];

        return collect($files)->map(fn (string $file) => [
            'source' => "public/assets/themes/prespa-saas/assets/img/ps-patterns/icons/features/{$file}.png",
            'destination' => "uploads/system/benefit-{$file}.png",
            'name' => ucfirst(str_replace('-', ' ', $file)) . ' Icon',
            'type' => 'image',
            'category' => 'benefit-icon',
            'alt_text' => ucfirst(str_replace('-', ' ', $file)) . ' icon',
        ])->all();
    }

    protected function caseStudyAssets(): array
    {
        return [
            [
                'source' => null,
                'destination' => 'uploads/system/case-study-1-before.svg',
                'name' => 'Case Study 1 Before Dashboard',
                'type' => 'image',
                'category' => 'case-study',
                'alt_text' => 'Before dashboard screenshot for lead generation case study',
                'inline' => $this->caseStudySvg('Before', '#F97316', '#94A3B8', '#FFE7D6'),
            ],
            [
                'source' => null,
                'destination' => 'uploads/system/case-study-1-after.svg',
                'name' => 'Case Study 1 After Dashboard',
                'type' => 'image',
                'category' => 'case-study',
                'alt_text' => 'After dashboard screenshot for lead generation case study',
                'inline' => $this->caseStudySvg('After', '#22C55E', '#2563EB', '#DCFCE7'),
            ],
            [
                'source' => null,
                'destination' => 'uploads/system/case-study-2-before.svg',
                'name' => 'Case Study 2 Before Dashboard',
                'type' => 'image',
                'category' => 'case-study',
                'alt_text' => 'Before dashboard screenshot for paid media reporting case study',
                'inline' => $this->caseStudySvg('Before', '#FB7185', '#94A3B8', '#FFE4E6'),
            ],
            [
                'source' => null,
                'destination' => 'uploads/system/case-study-2-after.svg',
                'name' => 'Case Study 2 After Dashboard',
                'type' => 'image',
                'category' => 'case-study',
                'alt_text' => 'After dashboard screenshot for paid media reporting case study',
                'inline' => $this->caseStudySvg('After', '#0EA5E9', '#8B5CF6', '#DBEAFE'),
            ],
        ];
    }

    protected function heroSvg(): string
    {
        return <<<'SVG'
<svg width="1440" height="960" viewBox="0 0 1440 960" fill="none" xmlns="http://www.w3.org/2000/svg">
  <rect width="1440" height="960" rx="52" fill="url(#bg)"/>
  <circle cx="1168" cy="170" r="118" fill="url(#glow)" fill-opacity="0.55"/>
  <circle cx="269" cy="223" r="140" fill="#FFFFFF" fill-opacity="0.08"/>
  <path d="M180 720C270 640 415 635 515 695C612 753 745 757 830 690C933 611 1088 612 1187 692L1260 751V870H180V720Z" fill="#FFFFFF" fill-opacity="0.08"/>
  <rect x="110" y="120" width="590" height="370" rx="34" fill="#FBFDFF" fill-opacity="0.98"/>
  <rect x="145" y="160" width="152" height="18" rx="9" fill="#D8E6FF"/>
  <rect x="145" y="198" width="110" height="12" rx="6" fill="#E7EEF9"/>
  <rect x="145" y="258" width="520" height="170" rx="28" fill="#F3F8FF"/>
  <path d="M192 388C243 324 309 303 370 312C429 320 462 372 518 370C571 369 618 320 666 280" stroke="url(#lineA)" stroke-width="12" stroke-linecap="round"/>
  <circle cx="192" cy="388" r="12" fill="#00C2FF"/>
  <circle cx="370" cy="312" r="12" fill="#7C3AED"/>
  <circle cx="518" cy="370" r="12" fill="#FF60C8"/>
  <circle cx="666" cy="280" r="12" fill="#1D4ED8"/>
  <rect x="764" y="160" width="566" height="620" rx="38" fill="#0F1939" fill-opacity="0.96"/>
  <rect x="814" y="214" width="168" height="22" rx="11" fill="#D8E6FF" fill-opacity="0.18"/>
  <rect x="814" y="250" width="114" height="12" rx="6" fill="#D8E6FF" fill-opacity="0.12"/>
  <rect x="814" y="314" width="214" height="188" rx="30" fill="#121F4A"/>
  <rect x="1050" y="314" width="224" height="188" rx="30" fill="#121F4A"/>
  <rect x="814" y="528" width="460" height="180" rx="30" fill="#121F4A"/>
  <path d="M857 462V372" stroke="#00C2FF" stroke-width="14" stroke-linecap="round"/>
  <path d="M906 462V396" stroke="#4F46E5" stroke-width="14" stroke-linecap="round"/>
  <path d="M955 462V350" stroke="#FF60C8" stroke-width="14" stroke-linecap="round"/>
  <path d="M1004 462V336" stroke="#38BDF8" stroke-width="14" stroke-linecap="round"/>
  <circle cx="1162" cy="408" r="58" stroke="#93C5FD" stroke-width="18"/>
  <path d="M1162 350C1186 350 1209 359 1226 376" stroke="#FF60C8" stroke-width="18" stroke-linecap="round"/>
  <path d="M1220 471C1203 489 1181 500 1156 500" stroke="#00C2FF" stroke-width="18" stroke-linecap="round"/>
  <path d="M862 642L937 582L1011 620L1098 548L1187 602" stroke="url(#lineB)" stroke-width="12" stroke-linecap="round" stroke-linejoin="round"/>
  <circle cx="862" cy="642" r="10" fill="#00C2FF"/>
  <circle cx="937" cy="582" r="10" fill="#1D4ED8"/>
  <circle cx="1011" cy="620" r="10" fill="#7C3AED"/>
  <circle cx="1098" cy="548" r="10" fill="#38BDF8"/>
  <circle cx="1187" cy="602" r="10" fill="#FF60C8"/>
  <defs>
    <linearGradient id="bg" x1="166" y1="65" x2="1288" y2="884" gradientUnits="userSpaceOnUse">
      <stop stop-color="#EEF6FF"/>
      <stop offset="0.4" stop-color="#E2EAFF"/>
      <stop offset="1" stop-color="#F5EEFF"/>
    </linearGradient>
    <radialGradient id="glow" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(1168 170) rotate(90) scale(118)">
      <stop stop-color="#7C3AED"/>
      <stop offset="1" stop-color="#7C3AED" stop-opacity="0"/>
    </radialGradient>
    <linearGradient id="lineA" x1="192" y1="350" x2="666" y2="285" gradientUnits="userSpaceOnUse">
      <stop stop-color="#00C2FF"/>
      <stop offset="0.5" stop-color="#7C3AED"/>
      <stop offset="1" stop-color="#FF60C8"/>
    </linearGradient>
    <linearGradient id="lineB" x1="862" y1="642" x2="1187" y2="602" gradientUnits="userSpaceOnUse">
      <stop stop-color="#00C2FF"/>
      <stop offset="0.5" stop-color="#4F46E5"/>
      <stop offset="1" stop-color="#FF60C8"/>
    </linearGradient>
  </defs>
</svg>
SVG;
    }

    protected function caseStudySvg(string $label, string $accent, string $secondary, string $panel): string
    {
        return <<<SVG
<svg width="1200" height="760" viewBox="0 0 1200 760" fill="none" xmlns="http://www.w3.org/2000/svg">
  <rect width="1200" height="760" rx="34" fill="#F8FBFF"/>
  <rect x="42" y="42" width="1116" height="676" rx="28" fill="#FFFFFF" stroke="#D6E5FF" stroke-width="4"/>
  <rect x="78" y="86" width="220" height="26" rx="13" fill="{$panel}"/>
  <rect x="78" y="132" width="152" height="16" rx="8" fill="#E5EEF9"/>
  <rect x="78" y="190" width="478" height="214" rx="22" fill="#F4F9FF"/>
  <rect x="592" y="190" width="530" height="214" rx="22" fill="#F4F9FF"/>
  <rect x="78" y="438" width="1044" height="226" rx="22" fill="#F4F9FF"/>
  <path d="M124 360C175 295 246 276 313 288C365 297 405 335 462 338C506 341 545 319 598 255" stroke="{$accent}" stroke-width="14" stroke-linecap="round"/>
  <circle cx="124" cy="360" r="12" fill="{$accent}"/>
  <circle cx="313" cy="288" r="12" fill="{$secondary}"/>
  <circle cx="462" cy="338" r="12" fill="#F97316"/>
  <circle cx="598" cy="255" r="12" fill="#22C55E"/>
  <path d="M652 352L713 312L775 332L845 262L920 282L996 228L1064 250" stroke="{$secondary}" stroke-width="14" stroke-linecap="round" stroke-linejoin="round"/>
  <circle cx="652" cy="352" r="10" fill="{$secondary}"/>
  <circle cx="775" cy="332" r="10" fill="{$accent}"/>
  <circle cx="920" cy="282" r="10" fill="#22C55E"/>
  <circle cx="1064" cy="250" r="10" fill="#0EA5E9"/>
  <rect x="118" y="484" width="140" height="118" rx="18" fill="#FFFFFF"/>
  <rect x="286" y="484" width="140" height="118" rx="18" fill="#FFFFFF"/>
  <rect x="454" y="484" width="140" height="118" rx="18" fill="#FFFFFF"/>
  <rect x="622" y="484" width="220" height="118" rx="18" fill="#FFFFFF"/>
  <rect x="870" y="484" width="208" height="118" rx="18" fill="#FFFFFF"/>
  <text x="88" y="88" fill="#0F172A" font-size="28" font-family="Arial, sans-serif" font-weight="700">{$label} dashboard</text>
  <text x="88" y="638" fill="#475569" font-size="18" font-family="Arial, sans-serif">Snapshot view for case study presentation</text>
</svg>
SVG;
    }
}
