<?php

namespace Kylin\Storage\Http\Controllers;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Kylin\Core\ApiResponse;
use Kylin\Core\Controllers\BaseController;
use Kylin\Storage\Models\File;
use Kylin\Storage\Services\StorageService;

class StorageController extends BaseController
{
    public function __construct(private readonly StorageService $service) {}

    public function upload(Request $request): JsonResponse
    {
        $request->validate([
            'file' => 'required|file|max:' . config('kylin-storage.max_file_size', 10240),
            'driver' => 'nullable|string|in:local,qiniu,tencent,aliyun,huawei,s3,kingsoft,baidu',
            'collection' => 'nullable|string|max:50',
        ]);

        $collection = $request->input('collection', 'default');
        $driver = $request->input('driver');
        $file = $this->service->upload($request->file('file'), $collection, $driver);

        return ApiResponse::created($file);
    }

    public function show(int $file): JsonResponse
    {
        $fileModel = File::findOrFail($file);
        return ApiResponse::success($fileModel);
    }

    public function signedUrl(int $file, Request $request): JsonResponse
    {
        $fileModel = File::findOrFail($file);
        $expires = $request->input('expires', 3600);
        $url = $fileModel->getSignedUrl((int) $expires);

        return ApiResponse::success(['url' => $url]);
    }

    public function delete(int $file): JsonResponse
    {
        $fileModel = File::findOrFail($file);
        $this->service->delete($fileModel);
        return ApiResponse::success(null, '删除成功');
    }
}
