<?php

namespace App\Services\Admin\Master\RawMaterial;

use App\Models\RawMaterial;
use App\Models\RawMaterialPrice;
use App\Services\Concerns\RegistersMedia;
use App\Services\NotificationService;
use App\Services\S3PresignedService;
use Illuminate\Support\Facades\DB;

class RawMaterialVariantService
{
    use RegistersMedia;

    public function __construct(
        private readonly S3PresignedService $s3Service,
    ) {}

    public function getForEdit(RawMaterialPrice $variant): array
    {
        $variant->load('media');

        $media = $variant->getMedia('photos');
        $photoKey = $media->first()?->file_name;
        $photoUrl = $media->first()
            ? $this->s3Service->getTemporaryUrl($media->first()->file_name)
            : null;

        return [
            'id' => $variant->id,
            'raw_material_id' => $variant->raw_material_id,
            'variant' => $variant->variant,
            'price' => $variant->price,
            'stock' => $variant->stock,
            'photo_key' => $photoKey,
            'photo_url' => $photoUrl,
        ];
    }

    public function update(RawMaterialPrice $variant, array $data): RawMaterialPrice
    {
        DB::transaction(function () use ($variant, $data) {
            $variant->update([
                'variant' => $data['variant'],
                'price' => $data['price'],
                'stock' => $data['stock'],
            ]);

            if (array_key_exists('photo_key', $data)) {
                $existingKey = $variant->getMedia('photos')->first()?->file_name;
                $newKey = $data['photo_key'];

                if ($existingKey !== $newKey) {
                    $variant->clearMediaCollection('photos');
                    if ($newKey) {
                        $this->registerPhoto($variant, $newKey);
                    }
                }
            }
        });

        NotificationService::notify(
            roles: ['Owner', 'Developer', 'Direktur', 'Admin Toko'],
            title: 'Varian Diperbarui',
            body: "Varian \"{$variant->variant}\" berhasil diperbarui".' oleh '.auth()->user()->full_name.'.',
            url: route('admin.master.raw-materials.index'),
        );

        return $variant->fresh();
    }

    public function delete(RawMaterial $rawMaterial, RawMaterialPrice $variant): bool
    {
        $result = DB::transaction(function () use ($variant) {
            $variant->clearMediaCollection('photos');

            return $variant->delete();
        });

        NotificationService::notify(
            roles: ['Owner', 'Developer', 'Direktur', 'Admin Toko'],
            title: 'Varian Dihapus',
            body: "Varian \"{$variant->variant}\" dari bahan baku \"{$rawMaterial->name}\" berhasil dihapus".' oleh '.auth()->user()->full_name.'.',
            url: route('admin.master.raw-materials.index'),
        );

        return $result;
    }

    private function registerPhoto(RawMaterialPrice $variant, string $s3Key): void
    {
        $this->registerMedia(
            model: $variant,
            s3Key: $s3Key,
            collectionName: 'photos',
            orderColumn: 1,
        );
    }
}
