<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\Merchant;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

final class AuthController extends Controller
{
    public function register(Request $request)
    {
        $data = $request->validate([
            'name' => 'required|string|max:120',
            'email' => 'required|email|max:255|unique:merchants,email',
            'password' => 'required|string|min:12|confirmed',
        ]);

        $merchant = Merchant::create([
            'public_id' => 'mrc_'.Str::ulid(),
            'name' => $data['name'],
            'email' => strtolower($data['email']),
            'password' => $data['password'],
            'status' => 'pending',
        ]);

        $merchant->sendEmailVerificationNotification();

        return ApiResponse::success([
            'merchant' => $merchant,
            'token' => $merchant->createToken('api')->plainTextToken,
        ], 201);
    }

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

        $merchant = Merchant::where('email', strtolower($data['email']))->first();

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

        if (in_array($merchant->status, ['suspended', 'closed'], true)) {
            return ApiResponse::error('MERCHANT_INACTIVE', 'Merchant account is not active.', 403);
        }

        $merchant->forceFill(['last_login_at' => now()])->save();

        return ApiResponse::success([
            'merchant' => $merchant,
            'token' => $merchant->createToken('api')->plainTextToken,
        ]);
    }

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

        return ApiResponse::success(['message' => 'Logged out.']);
    }

    public function me(Request $request)
    {
        return ApiResponse::success($request->user());
    }
}