<?php

namespace App\Modules\CustomerPortal\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Responses\ApiResponse;
use App\Modules\CustomerPortal\Models\CustomerPortalAccount;
use App\Modules\CustomerPortal\Requests\LoginCustomerPortalRequest;
use App\Modules\CustomerPortal\Requests\UpdateCustomerPortalProfileRequest;
use App\Modules\CustomerPortal\Resources\CustomerPortalAccountResource;
use App\Modules\Tenant\Models\Company;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class CustomerPortalAuthController extends Controller
{
    public function login(LoginCustomerPortalRequest $request): JsonResponse
    {
        $data = $request->validated();

        $company = Company::query()
            ->where('slug', $data['company_slug'])
            ->where('status', 'active')
            ->first();

        if (! $company) {
            return ApiResponse::error('Invalid credentials', 422);
        }

        $account = CustomerPortalAccount::query()
            ->with(['customer', 'company'])
            ->where('company_id', $company->id)
            ->where('email', $data['email'])
            ->where('status', 'active')
            ->first();

        if (! $account || ! Hash::check($data['password'], $account->password)) {
            return ApiResponse::error('Invalid credentials', 422);
        }

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

        $token = $account->createToken($data['device_name'] ?? 'customer-portal')->plainTextToken;

        return ApiResponse::success([
            'account' => new CustomerPortalAccountResource($account->fresh(['customer', 'company'])),
            'token' => $token,
            'token_type' => 'Bearer',
        ], 'Customer logged in successfully');
    }

    public function me(Request $request): JsonResponse
    {
        $account = $this->currentAccount($request);

        if (! $account) {
            return ApiResponse::error('Customer portal account required', 403);
        }

        return ApiResponse::success(
            new CustomerPortalAccountResource($account->loadMissing(['customer', 'company']))
        );
    }

    public function updateProfile(UpdateCustomerPortalProfileRequest $request): JsonResponse
    {
        $account = $this->currentAccount($request);

        if (! $account) {
            return ApiResponse::error('Customer portal account required', 403);
        }

        $data = $request->validated();

        if (! blank($data['password'] ?? null)) {
            if (! Hash::check((string) $data['current_password'], $account->password)) {
                return ApiResponse::error('Current password is incorrect', 422);
            }

            $account->password = $data['password'];
            $currentToken = $account->currentAccessToken();
            $account->tokens()
                ->when($currentToken, fn ($query) => $query->whereKeyNot($currentToken->id))
                ->delete();
        }

        $account->name = $data['name'];
        $account->email = $data['email'];
        $account->save();

        return ApiResponse::success(
            new CustomerPortalAccountResource($account->fresh(['customer', 'company'])),
            'Customer portal profile updated successfully'
        );
    }

    public function logout(Request $request): JsonResponse
    {
        $account = $this->currentAccount($request);

        if (! $account) {
            return ApiResponse::error('Customer portal account required', 403);
        }

        $account->currentAccessToken()?->delete();

        return ApiResponse::success(null, 'Customer logged out successfully');
    }

    private function currentAccount(Request $request): ?CustomerPortalAccount
    {
        $user = $request->user();

        return $user instanceof CustomerPortalAccount && $user->status === 'active' ? $user : null;
    }
}
