<?php

namespace App\Modules\HR\Recruitment\Services;

use App\Modules\HR\Recruitment\Models\RecruitmentOfferLetter;
use App\Modules\HR\Recruitment\Models\RecruitmentOfferLetterAttachment;
use App\Modules\HR\Recruitment\Repositories\RecruitmentOfferLetterAttachmentRepository;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;

class RecruitmentOfferLetterAttachmentService
{
    public function __construct(
        private readonly RecruitmentOfferLetterAttachmentRepository $repository,
    ) {}

    public function store(RecruitmentOfferLetter $offer, UploadedFile $file, int $userId): RecruitmentOfferLetterAttachment
    {
        $path = $file->store(
            'tenants/'.$offer->tenant_id.'/recruitment/offers/'.$offer->id.'/attachments',
            'local'
        );

        return $this->repository->create([
            'tenant_id' => (int) $offer->tenant_id,
            'offer_letter_id' => (int) $offer->id,
            'file_path' => $path,
            'original_name' => $file->getClientOriginalName(),
            'file_size' => (int) $file->getSize(),
            'mime_type' => $file->getClientMimeType(),
            'uploaded_by' => $userId,
        ]);
    }

    public function destroy(RecruitmentOfferLetterAttachment $attachment): void
    {
        if ($attachment->file_path && Storage::disk('local')->exists($attachment->file_path)) {
            Storage::disk('local')->delete($attachment->file_path);
        }
        $this->repository->softDelete($attachment);
    }
}
