<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Responses\ApiResponse;
use App\Models\OperationLog;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class OperationLogController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        try {
            $query = OperationLog::with('user:id,username,name');

            if ($request->filled('module')) {
                $query->where('module', $request->input('module'));
            }

            if ($request->filled('action')) {
                $query->where('action', 'like', '%'.$request->input('action').'%');
            }

            if ($request->filled('method')) {
                $query->where('method', $request->input('method'));
            }

            if ($request->filled('status')) {
                $query->where('status', $request->input('status'));
            }

            if ($request->filled('user_id')) {
                $query->where('user_id', $request->input('user_id'));
            }

            if ($request->filled('start_date')) {
                $query->where('create_time', '>=', $request->input('start_date').' 00:00:00');
            }

            if ($request->filled('end_date')) {
                $query->where('create_time', '<=', $request->input('end_date').' 23:59:59');
            }

            if ($request->filled('keyword')) {
                $keyword = $request->input('keyword');
                $query->where(function ($q) use ($keyword) {
                    $q->where('path', 'like', '%'.$keyword.'%')
                        ->orWhere('action', 'like', '%'.$keyword.'%')
                        ->orWhere('ip', 'like', '%'.$keyword.'%');
                });
            }

            $perPage = (int) $request->input('per_page', 20);
            $paginator = $query->orderBy('id', 'desc')->paginate($perPage);

            $items = $paginator->items();
            foreach ($items as $item) {
                $item->status_text = $item->status === 1 ? '成功' : '失败';
            }

            return response()->json(ApiResponse::paginate($paginator));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '获取操作日志列表失败：'.$e->getMessage()));
        }
    }

    public function show(int $id): JsonResponse
    {
        try {
            $log = OperationLog::with('user:id,username,name')->find($id);

            if (! $log) {
                return response()->json(ApiResponse::error(40302, '日志记录不存在'));
            }

            return response()->json(ApiResponse::success($log));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '获取日志详情失败：'.$e->getMessage()));
        }
    }

    public function destroy(Request $request): JsonResponse
    {
        try {
            $ids = $request->input('ids', []);

            if (empty($ids)) {
                $id = $request->input('id');
                if ($id) {
                    $ids = [$id];
                }
            }

            if (empty($ids)) {
                return response()->json(ApiResponse::error(40201, '请选择要删除的记录'));
            }

            $deleted = OperationLog::destroy($ids);

            return response()->json(ApiResponse::success(['deleted' => $deleted], '删除成功'));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '删除日志失败：'.$e->getMessage()));
        }
    }

    public function clear(Request $request): JsonResponse
    {
        try {
            $days = (int) $request->input('days', 30);

            $cutoff = now()->subDays($days);
            $deleted = OperationLog::where('create_time', '<', $cutoff)->delete();

            return response()->json(ApiResponse::success(['deleted' => $deleted], "已清理 {$days} 天前的日志共 {$deleted} 条"));
        } catch (\Exception $e) {
            return response()->json(ApiResponse::error(50001, '清理日志失败：'.$e->getMessage()));
        }
    }

    public function modules(): JsonResponse
    {
        try {
            $modules = OperationLog::select('module')
                ->distinct()
                ->orderBy('module')
                ->pluck('module');

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