<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use App\Models\User;
use App\Models\Log;
use Carbon\Carbon;
use App\Http\Controllers\ProjectController;

class TokenAuthController extends Controller
{
    protected $connection = 'mongodb'; // 指定使用的數據庫連接

    public function analyzeToken(Request $request)
    {
        $token = $request->token;

        try {
            $payload = JWTAuth::setToken($token)->getPayload();
            $account = $payload['sub'];
            $page = $payload['page'];
            $user = User::where('account', $account)->first();

            if (!$user) {
                return response()->json(['error' => 'No user found for this token'], 404);
            }

            $allPermissions = $user->getAllPermissions()->pluck('name');
            $abilities = [];
            $token_abilities = [];

            array_map(function ($permission) use (&$abilities, &$token_abilities) {
                list($action, $subject) = explode(' ', $permission, 2);

                $abilities[] = [
                    'action' => $action,
                    'subject' => $subject
                ];

                $token_abilities[] = $action . '_' . $subject;
            }, $allPermissions->toArray());

            $token = $user->createToken('KM-token', $token_abilities)->plainTextToken;

            $transformedUserData = $this->transformUserData($user);

            return response()->json([
                'userData' => $transformedUserData,
                'accessToken' => $token,
                'userAbilityRules' => $abilities,
                'page' => $page,
            ]);
        } catch (JWTException $e) {
            // Token 驗證失敗
            return response()->json(['error' => $e->getMessage()], 401);
        }
    }

    protected function transformUserData(User $user)
    {
        return [
            'id' => $user->UserID,
            'userId' => $user->UserID,
            'deptNo' => $user->DeptNo,
            'deptName' => $user->DeptName,
            'jobTitle' => $user->JobTitle,
            'gradeName' => $user->GradeName,
            'username' => $user->UserName,
            'account' => $user->Account,
            'role' => $user->getRoleNames(),
        ];
    }

    public function createToken(Request $request)
    {
        // 从请求中获取 JWT
        $token = $request->token;

        try {
            // 解析 JWT
            $payload = JWTAuth::setToken($token)->getPayload();
            $_id = $payload['sub'];
            $project_id = $payload['project_id'];
            $project = ProjectController::getProject($project_id);
            $project_number = $project['no'];
            $project_name = $project['name'];
            $startDate = $project['expectedBeginAt'];
            $work_duration = $project['work_duration'];

            // 通过账号查找用户
            $user = User::where('_id', $_id)->first();

            if (!$user) {
                $this->logAction('查無此帳號', '失敗', $project_number, $_id);
                return response()->json(['error' => 'No user found for this account'], 404);
            }

            // 使用 Sanctum 发行 token
            $sanctumToken = $user->createToken('PDET-token')->plainTextToken;

            $abilities[] = [
                'action' => 'read',
                'subject' => 'pdet'
            ];

            $this->logAction('登入工期試算工具系統', '成功', $project_number, $user->name);

            return response()->json([
                'userData' => [
                    'id' => $user->_id,
                    'name' => $user->name,
                    'email' => $user->email,
                    'phone' => $user->phone,
                ],
                'project_number' => $project_number,
                'project_name' => $project_name,
                'startDate' => $startDate,
                'work_duration' => $work_duration,
                'accessToken' => $sanctumToken,
                'userAbilityRules' => $abilities,

            ]);
        } catch (JWTException $e) {
            $payload = JWTAuth::setToken($token)->getPayload();
            $_id = $payload['sub'];
            $project_number = $project['no'];

            $this->logAction('登入工期試算工具系統', '失敗', $project_number, $_id);
            return response()->json(['error' => $e->getMessage()], 401);
        }
    }

    private function logAction($action_content, $action_result, $project_number, $user)
    {
        Log::create([
            'user' => $user,
            'project_number' => $project_number,
            'action_type' => '登入',
            'action_content' => $action_content,
            'action_result' => $action_result,
            'action_timestamp' => Carbon::now('Asia/Taipei'),
        ]);
    }
}
