<?php

namespace App\Traits;

use App\Models\Attachment;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;

trait UploadAttachment
{
    public function uploadAttachment(UploadedFile|string $file, string $path, string $classModel, string $featureId, string $type): void
    {
        DB::transaction(function () use ($file, $path, $classModel, $featureId, $type) {
            if (is_string($file) && strpos($file, 'data:image') === 0) {
                $imageData = explode(',', $file)[1];
                $image = base64_decode($imageData);
                $extension = 'png';
                $fileName = Str::uuid();
                $fullFileName = $fileName.'.'.$extension;

                $date = now()->format('Y-m-d');
                Storage::disk('public')->put($path.'/'.$date.'/'.$fullFileName, $image);

                Attachment::updateOrCreate(
                    [
                        'attachmentable_id' => $featureId,
                        'attachmentable_type' => $classModel,
                        'type' => $type,
                    ],
                    [
                        'name' => $fileName,
                        'extension' => $extension,
                        'size' => strlen($image),
                    ]
                );
            } elseif ($file instanceof UploadedFile) {
                $date = now()->format('Y-m-d');
                $extension = $file->getClientOriginalExtension();
                $fileName = Str::uuid();
                $file->storeAs($path.'/'.$date, $fileName.'.'.$extension, 'public');

                Attachment::updateOrCreate(
                    [
                        'attachmentable_id' => $featureId,
                        'attachmentable_type' => $classModel,
                        'type' => $type,
                    ],
                    [
                        'name' => $fileName,
                        'extension' => $extension,
                        'size' => $file->getSize(),
                    ]
                );
            }
        });
    }
}
