<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use App\Services\AuthService;
use Illuminate\Http\Request;
use App\Traits\ApiResponse;

class AuthController extends Controller
{
    use ApiResponse;

    protected $authService;

    public function __construct(AuthService $authService)
    {
        $this->authService = $authService;
    }

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

        try {
            $result = $this->authService->login($request->all(), $request->ip());

            if (isset($result['error']) && $result['error'] === 'lockout') {
                return $this->errorResponse(
                    $result['error'], 
                    429, 
                    [
                        'seconds_remaining' => $result['seconds'],
                        'locked_until'      => $result['until']
                    ]
                );
            }

            if (isset($result['error'])) {
                return $this->errorResponse($result['error'], 401);
            }

            return $this->successResponse([
                'access_token' => $result['token'],
                'user' => new UserResource($result['user']),
            ], 'login success', 200);
        } catch(\Exception $e) {
            return $this->errorResponse('internal server error', 500, $e->getMessage());
        }
    }

    public function register(Request $request)
    {
        $data = $request->validate([
            'business_name'         => 'required|string|max:255',
            'business_code'         => 'required|string|unique:tenants,business_code',
            'name'                  => 'required|string|max:255',
            'phone_number'          => 'required|string|unique:users,phone_number',
            'email'                 => 'nullable|email|unique:users,email',
            'password'              => 'required|min:8|confirmed',
            'password_confirmation' => 'required|min:8'
        ], [
            'phone_number.unique' => 'phone number already exists',
            'email.unique'        => 'email already exists',
        ]);

        try {
            $result = $this->authService->register($data);
            
            return $this->successResponse([
                'business_code' => $result['business_code'],
                'owner_name'    => $result['user']->name,
            ], 'registration success', 201);
        } catch (\Exception $e) {
            return $this->errorResponse('internal server error', 500, $e->getMessage());
        }
    }
}
