<?php

declare(strict_types=1);

namespace App\Services;

use App\Models\Member;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Intervention\Image\Drivers\Gd\Driver;
use Intervention\Image\ImageManager;

/**
 * Photos are processed inline at upload (single image, fast) per
 * docs/01-architecture.md — never batch-processed in a request.
 */
class MemberPhotoService
{
    private const FULL_MAX = 800;

    private const THUMB_SIZE = 160;

    private const JPEG_QUALITY = 85;

    private readonly ImageManager $manager;

    public function __construct()
    {
        $this->manager = new ImageManager(new Driver);
    }

    public function store(Member $member, UploadedFile $file): void
    {
        $directory = "members/{$member->id}";
        Storage::disk('local')->makeDirectory($directory);

        $fullPath = Storage::disk('local')->path("{$directory}/photo_full.jpg");
        $thumbPath = Storage::disk('local')->path("{$directory}/photo_thumb.jpg");

        $this->manager->decodePath($file->getRealPath())
            ->scaleDown(width: self::FULL_MAX, height: self::FULL_MAX)
            ->save($fullPath, quality: self::JPEG_QUALITY);

        $this->manager->decodePath($file->getRealPath())
            ->cover(self::THUMB_SIZE, self::THUMB_SIZE)
            ->save($thumbPath, quality: self::JPEG_QUALITY);

        $member->forceFill(['photo_path' => $directory])->saveQuietly();
    }

    public function absolutePath(Member $member, string $size): ?string
    {
        if ($member->photo_path === null) {
            return null;
        }

        $filename = $size === 'full' ? 'photo_full.jpg' : 'photo_thumb.jpg';
        $path = Storage::disk('local')->path("{$member->photo_path}/{$filename}");

        return is_file($path) ? $path : null;
    }
}
