<?php

namespace App\Services;

use App\Models\WhatWeDoImage;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

class WhatWeDoImageService
{
    /**
     * Canonical mapping of slot number → card title.
     * Slots are fixed identifiers 1–9.
     */
    private const SLOT_TITLES = [
        1 => 'Annual Conferences',
        2 => 'National & International Programs',
        3 => 'Governing Board & Membership',
        4 => 'Workshops & Seminars',
        5 => 'Guidelines & Standards',
        6 => 'International Partnerships',
        7 => 'Capacity Building',
        8 => 'Policy Advocacy',
        9 => 'Fundraising',
    ];

    /**
     * Return all 9 slot records ordered by slot ascending.
     * Creates any missing slot records with the canonical card title and null image_path.
     */
    public function getAllSlots(): Collection
    {
        foreach (self::SLOT_TITLES as $slot => $title) {
            WhatWeDoImage::firstOrCreate(
                ['slot' => $slot],
                ['card_title' => $title, 'image_path' => null]
            );
        }

        return WhatWeDoImage::ordered()->get();
    }

    /**
     * Store a new image for the given slot, replacing any existing file.
     * Generates a unique filename to prevent collisions.
     */
    public function updateSlotImage(int $slot, UploadedFile $file): WhatWeDoImage
    {
        $record = WhatWeDoImage::firstOrCreate(
            ['slot' => $slot],
            ['card_title' => self::SLOT_TITLES[$slot] ?? "Slot {$slot}", 'image_path' => null]
        );

        // Delete the old file if one exists
        if ($record->image_path && Storage::disk('public')->exists($record->image_path)) {
            Storage::disk('public')->delete($record->image_path);
        } elseif ($record->image_path) {
            Log::warning("WhatWeDoImageService: old file not found for slot {$slot}: {$record->image_path}");
        }

        // Generate a unique filename and store the new file
        $extension = $file->getClientOriginalExtension();
        $filename  = 'what-we-do/' . Str::uuid() . '.' . $extension;

        Storage::disk('public')->putFileAs('what-we-do', $file, basename($filename));

        $record->update(['image_path' => $filename]);

        return $record->fresh();
    }

    /**
     * Return the public URL for the stored image of a slot, or null if none uploaded.
     */
    public function getImageUrl(int $slot): ?string
    {
        $record = WhatWeDoImage::where('slot', $slot)->first();

        if (! $record || ! $record->image_path) {
            return null;
        }

        return Storage::disk('public')->url($record->image_path);
    }

    /**
     * Remove the stored file for a slot and clear its image_path.
     */
    public function deleteSlotImage(int $slot): bool
    {
        $record = WhatWeDoImage::where('slot', $slot)->first();

        if (! $record) {
            return false;
        }

        if ($record->image_path && Storage::disk('public')->exists($record->image_path)) {
            Storage::disk('public')->delete($record->image_path);
        }

        $record->update(['image_path' => null]);

        return true;
    }
}
