<?php
// +----------------------------------------------------------------------
// | onezan-admin 快速开发的管理平台
// +----------------------------------------------------------------------
// | 官方网址：https://www.onezan.cn
// +----------------------------------------------------------------------
// | onezan团队 版权所有 开源版本可自由商用
// +----------------------------------------------------------------------
// | Author: 543885307@qq.com
// +----------------------------------------------------------------------
namespace app\service\api\media;

use app\service\api\BaseApiService;
use app\service\domain\media\CoreMediaService;
use think\facade\Log;
use think\Request;


/**
 * Media Service
 * @package app\service\api\media
 */
class MediaService extends BaseApiService
{

    /**
     * 上传媒体文件
     * @param Request $request 请求对象
     * @return array
     */
    public function upload(Request $request): array
    {
        $uid = $request->uid ?? null;
        if (!$uid) {
            return ['code' => 401, 'msg' => '', '_http_status' => 401];
        }

        $file = $request->file('file');
        if (!$file) {
            return ['code' => 1, 'msg' => ''];
        }

        $type = trim((string)$request->post('type', ''));
        $groupId = 0;

        try {
            return ['code' => 0, 'msg' => '', 'data' => $this->core()->saveUpload($file, $type, $groupId)];
        } catch (\RuntimeException $e) {
            return ['code' => 1, 'msg' => $e->getMessage()];
        } catch (\Throwable $e) {
            Log::error('api media upload failed: ' . $e->getMessage(), [
                'type' => $type,
                'uid' => $uid,
                'exception' => get_class($e),
                'file' => $e->getFile(),
                'line' => $e->getLine(),
            ]);
            return ['code' => 1, 'msg' => app()->isDebug() ? $e->getMessage() : ''];
        }
    }

    /**
     * 获取媒体核心服务实例
     * @return CoreMediaService
     */
    private function core(): CoreMediaService
    {
        return $this->app->make(CoreMediaService::class);
    }
}