<?php

namespace App\Http\Controllers\File;

use App\Http\Controllers\ApiController;
use App\Http\Requests\File\IndexStoredFileRequest;
use App\Http\Requests\File\StoreFileRequest;
use App\Http\Resources\File\StoredFileResource;
use App\Models\StoredFile;
use App\Services\File\StoredFileService;
use Illuminate\Http\Request;

class StoredFileController extends ApiController
{
    public function __construct(protected StoredFileService $service) {}

    public function index(IndexStoredFileRequest $request)
    {
        return $this->successPaginated(
            $this->service->list(
                $request->validated(),
                $request->user(),
                $request->attributes->get('tenant_id')
            ),
            StoredFileResource::class,
            'Daftar file berhasil diambil'
        );
    }

    public function store(StoreFileRequest $request)
    {
        $file = $this->service->store(
            $request->file('file'),
            $request->user(),
            $request->attributes->get('tenant_id'),
            $request->validated('category', 'general')
        );

        return $this->created(new StoredFileResource($file), 'File berhasil diunggah');
    }

    public function show(Request $request, StoredFile $storedFile)
    {
        $this->service->authorizeAccess($storedFile, $request->user());

        return $this->success(new StoredFileResource($storedFile), 'Detail file berhasil diambil');
    }

    public function temporaryUrl(Request $request, StoredFile $storedFile)
    {
        return $this->success(
            $this->service->temporaryUrl($storedFile, $request->user()),
            'URL sementara berhasil dibuat'
        );
    }

    public function destroy(Request $request, StoredFile $storedFile)
    {
        $this->service->delete($storedFile, $request->user());

        return $this->deleted('File berhasil dihapus');
    }
}
