<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Workspace;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
use Auth;

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $request->validate([
            'name' => 'required',
            'email' => 'required|email|unique:users',
            'password' => 'required|min:6|confirmed',
        ]);

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => bcrypt($request->password),
        ]);

        $token = $user->createToken('auth_token')->plainTextToken;
        $workspace = Workspace::create([
            'user_id' => $user->id,
            'name' => $user->name . "'s Workspace",
            'slug' => Str::slug($user->name) . '-' . time(),
        ]);
        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'status' => true,
            'message' => 'Registration successful',
            'workspace' => $workspace,
            'user' => $user,
            // 'roles' => $user->roles()->pluck('slug'),
            // 'permissions' => $user
            //     ->permissions()
            //     ->pluck('slug')
            //     ->values(),
        ]);
    }

    public function login(Request $request)
    {
        $request->validate([
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if (!Auth::attempt($request->only('email', 'password'))) {
            return response()->json([
                'status' => false,
                'message' => 'Invalid credentials'
            ], 401);
        }

        $user = Auth::user();

        $token = $user->createToken('auth_token')->plainTextToken;
        $workspaces = $user
            ->workspaceMemberships()
            ->with(['workspace', 'role'])
            ->get()
            ->map(function ($member) {
                return [
                    'id' => $member->workspace->id,
                    'name' => $member->workspace->name,
                    'role' => $member->role->name,
                ];
            });
        return response()->json([
            'status' => true,
            'message' => 'Login successful',
            'token' => $token,
            'user' => $user,
            'roles' => $user->roles()->pluck('name'),
            'workspaces' => $workspaces,
            'permissions' => $user
                ->roles()
                ->with('permissions')
                ->get()
                ->pluck('permissions')
                ->flatten()
                ->pluck('slug')
                ->unique()
                ->values(),
        ]);
    }

    public function profile(Request $request)
    {
        return response()->json([
            'status' => true,
            'user' => $request->user(),
        ]);
    }

    public function logout(Request $request)
    {
        $request->user()->currentAccessToken()->delete();

        return response()->json([
            'status' => true,
            'message' => 'Logout successful',
        ]);
    }

    public function assignRole(Request $request)
    {
        $request->validate([
            'user_id' => 'required|exists:users,id',
            'role_id' => 'required|exists:roles,id',
        ]);

        $user = User::findOrFail($request->user_id);

        $user->roles()->sync([
            $request->role_id
        ]);

        return response()->json([
            'status' => true,
            'message' => 'Role assigned successfully'
        ]);
    }
}
