<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Services\AttachmentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class AttachmentController extends Controller
{
    protected AttachmentService $attachmentService;

    public function __construct(AttachmentService $attachmentService)
    {
        $this->attachmentService = $attachmentService;
    }

    public function uploadConfig(): JsonResponse
    {
        try {
            $config = $this->attachmentService->getUploadConfigForFrontend();

            return response()->json([
                'code' => 0,
                'message' => 'success',
                'data' => $config,
                'timestamp' => time(),
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 50001,
                'message' => '获取上传配置失败：'.$e->getMessage(),
                'data' => null,
                'timestamp' => time(),
            ]);
        }
    }

    public function index(Request $request): JsonResponse
    {
        try {
            $result = $this->attachmentService->index($request->all());

            return response()->json($result);
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '获取附件列表失败：'.$e->getMessage()));
        }
    }

    public function upload(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'files' => 'required|array',
                'files.*' => 'file',
                'group_id' => 'nullable|integer',
            ]);

            $groupId = $request->input('group_id');
            $files = $request->file('files');
            $results = [];
            $errors = [];

            foreach ($files as $file) {
                $result = $this->attachmentService->upload($file, $groupId);
                if ($result['code'] !== 0) {
                    $errors[] = [
                        'name' => $file->getClientOriginalName(),
                        'message' => $result['message'],
                    ];
                } else {
                    $results[] = $result['data'];
                }
            }

            return response()->json([
                'code' => 0,
                'message' => empty($errors)
                    ? '全部上传成功'
                    : '部分文件上传失败',
                'data' => [
                    'success' => $results,
                    'failed' => $errors,
                    'success_count' => count($results),
                    'failed_count' => count($errors),
                ],
                'timestamp' => time(),
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 50001,
                'message' => '上传失败：'.$e->getMessage(),
                'data' => null,
                'timestamp' => time(),
            ]);
        }
    }

    public function show(int $id): JsonResponse
    {
        try {
            $result = $this->attachmentService->show($id);

            return response()->json($result);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 50001,
                'message' => '获取附件详情失败：'.$e->getMessage(),
                'data' => null,
                'timestamp' => time(),
            ]);
        }
    }

    public function destroy(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'ids' => 'required|array',
                'ids.*' => 'integer',
            ]);

            $result = $this->attachmentService->destroy($request->input('ids'));

            return response()->json($result);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 50001,
                'message' => '删除失败：'.$e->getMessage(),
                'data' => null,
                'timestamp' => time(),
            ]);
        }
    }

    public function moveGroup(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'ids' => 'required|array',
                'ids.*' => 'integer',
                'group_id' => 'nullable|integer',
            ]);

            $result = $this->attachmentService->moveGroup(
                $request->input('ids'),
                $request->input('group_id')
            );

            return response()->json($result);
        } catch (\Exception $e) {
            return response()->json([
                'code' => 50001,
                'message' => '移动分组失败：'.$e->getMessage(),
                'data' => null,
                'timestamp' => time(),
            ]);
        }
    }
}
