<?php

namespace App\Actions\V1\Project;

use App\Dto\V1\Project\ProjectDto;
use App\Models\InternalUser;
use App\Models\ProjectImage;
use App\Repositories\V1\Projects\ProjectImageRepositoryInterface;
use App\Repositories\V1\Projects\ProjectRepositoryInterface;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

readonly class StoreProjectAction
{
    public function __construct(
        private ProjectRepositoryInterface      $projectRepository,
        private ProjectImageRepositoryInterface $projectImageRepository
    ) {}

    public function execute(ProjectDto $dto, InternalUser $user): void
    {
        $storedPaths = [];

        DB::beginTransaction();
        try {
            $project = $this->projectRepository->store(
                $dto->projectStorePayload($user->id)
            );

            foreach ($dto->images ?? [] as $image) {
                if (!$image instanceof UploadedFile) {
                    continue;
                }

                $path = $image->store("projects/{$project->id}", 'public');
                $storedPaths[] = $path;

                ProjectImage::query()->create([
                    'project_id' => $project->id,
                    'image' => $path,
                ]);
            }
            DB::commit();
        } catch (\Throwable $e) {
            DB::rollBack();

            // cleanup files
            if (!empty($storedPaths)) {
                Storage::disk('public')->delete($storedPaths);
            }

            throw $e;
        }
    }
}
