<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

class AuthController extends Controller
{
    public function login(Request $request)
    {
        $data = $request->validate([
            'email' => ['required', 'string'],
            'password' => ['required', 'string'],
        ]);

        $user = User::where('email', $data['email'])->first();

        if (! $user || ! Hash::check($data['password'], $user->password)) {
            throw ValidationException::withMessages(['email' => ['Invalid credentials']]);
        }

        $token = $user->createToken('sms')->plainTextToken;
        ActivityLog::record('login', 'auth', "{$user->name} logged in");

        return response()->json([
            'user' => $user->only(['id', 'name', 'email', 'role', 'avatar', 'default_branch_id']),
            'token' => $token,
            'roles' => [$user->role],
            'permissions' => $user->isSuperAdmin() ? ['*'] : ($user->permissions ?? []),
            'branches' => $user->accessibleBranchIds(),
        ]);
    }

    public function logout(Request $request)
    {
        ActivityLog::record('logout', 'auth');
        $request->user()?->currentAccessToken()?->delete();

        return response()->json(['success' => true]);
    }

    public function me(Request $request)
    {
        $user = $request->user();

        return response()->json([
            'user' => $user->only(['id', 'name', 'email', 'role', 'avatar', 'default_branch_id']),
            'roles' => [$user->role],
            'permissions' => $user->isSuperAdmin() ? ['*'] : ($user->permissions ?? []),
            'branches' => $user->accessibleBranchIds(),
        ]);
    }
}
