<?php

namespace App\Http\Controllers\admin;

use App\Constants\HttpStatus;
use App\Constants\Util;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\ValidationException;
use Exception;

class Upload extends Controller
{
    /**
     * @api {post} /admin/upload/uploadFile 上传文件
     * @apiGroup Upload
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     * @apiParam {File} image 图像文件的路径（本地路径）
     * - 文件大小限制：最大 10MB。
     * - 支持图像格式：`jpg`, `jpeg`, `png`，`webp`。
     */
    public function store()
    {
        try {
            request()->validate([
                'image' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:10240'],
            ]);
            if (request()->hasFile('image')) {
                $image = request()->file('image');
                $imageName = md5_file($image->getRealPath());


                if ($image->getClientOriginalExtension() == '') {
                    $imageName .= '.webp';
                } else {
                    $imageName .= '.' . $image->getClientOriginalExtension();
                }


                $filePath = storage_path('app/public/images/' . $imageName);
                if (!file_exists($filePath)) {
                    $path = $image->storeAs('images', $imageName, 'public');
                    $path = Storage::url($path);
                } else {
                    $path = Storage::url('images/' . $imageName);
                }
            } else {
                throw new Exception('', HttpStatus::FILE_UPLOAD_ERROR);
            }
        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getCode());
        }
        return $this->success(['path' => Util::ensureUrl($path)]);
    }


    /**
     * @api {post} /admin/upload/uploadVideo 上传视频
     * @apiGroup Upload
     * @apiUse result
     * @apiUse header
     * @apiVersion 1.0.0
     * @apiParam {File} file 附件的路径（本地路径）
     * - 文件大小限制：最大 50MB。
     * - 支持视频格式：`mp4`,`mov`,`avi`,`webm`
     */
    public function video()
    {
        try {
            request()->validate([
                'file' => ['required', 'file', 'mimes:jpg,jpeg,png,webp,mp4,mov,avi,webm', 'max:51200'],// 最大 50MB，单位KB
            ]);
            if (request()->hasFile('file')) {
                $file = request()->file('file');
                $fileName = md5_file($file->getRealPath());
                // 获取原始扩展名
                $extension = $file->getClientOriginalExtension();
                $fileName .= $extension ? ('.' . $extension) : '';
                // 根据类型判断存放目录（可选）
                $isImage = in_array(strtolower($extension), ['jpg', 'jpeg', 'png', 'webp']);
                $dir = $isImage ? 'images' : 'videos';

                $filePath = storage_path("app/public/{$dir}/" . $fileName);
                if (!file_exists($filePath)) {
                    $path = $file->storeAs($dir, $fileName, 'public');
                    $path = Storage::url($path);
                } else {
                    $path = Storage::url("{$dir}/" . $fileName);
                }
            } else {
                throw new Exception('', HttpStatus::FILE_UPLOAD_ERROR);
            }

        } catch (ValidationException $e) {
            return $this->error(HttpStatus::CUSTOM_ERROR, $e->validator->errors()->first());
        } catch (Exception $e) {
            return $this->error($e->getCode(), $e->getMessage());
        }

        return $this->success(['path' => Util::ensureUrl($path)]);
    }
}
