<?php

namespace App\Services;

use App\Repositories\Eloquent\DisbursementManagementRepository;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

class DisbursementManagementService
{
    public function __construct(
        private DisbursementManagementRepository $repository,
        private PayoutNotificationService $notificationService,
    ) {}

    public function index(array $filters = []): array
    {
        return [
            'stats' => $this->repository->stats(),
            'eligible' => $this->repository->eligible($filters),
            'history' => $this->repository->history($filters),
        ];
    }

    public function release(array $bookingIds, array $uploadedProofs): array
    {
        $proofs = [];
        try {
            foreach ($uploadedProofs as $professionalId => $file) {
                if (! $file instanceof UploadedFile) {
                    continue;
                }
                $path = $file->store('payout-proofs/'.now()->format('Y/m'), 'payout_proofs');
                if (! $path) {
                    throw new \RuntimeException('The proof of payment could not be stored.');
                }
                $proofs[(int) $professionalId] = [
                    'path' => $path,
                    'original_name' => $file->getClientOriginalName(),
                    'mime_type' => $file->getMimeType() ?: $file->getClientMimeType(),
                ];
            }
            $result = $this->repository->release(array_values(array_unique(array_map('intval', $bookingIds))), $proofs);
        } catch (\Throwable $exception) {
            foreach ($proofs as $proof) {
                Storage::disk('payout_proofs')->delete($proof['path']);
            }
            throw $exception;
        }

        $result['email_failures'] = $this->notificationService->send($result['records']);

        return $result;
    }
}
