<?php

namespace App\Http\Controllers\Api\Account;

use App\Http\Controllers\Controller;
use App\Services\AccountService;
use App\Http\Requests\Api\Account\AccountContactsRequest;
use App\Models\Account\Account;
use App\Exceptions\ApiHttpException;
use App\Http\Requests\Api\Account\AccountNameRequest;
use App\Http\Resources\Account\Account as AccountResource;
use Illuminate\Http\Request;

class AccountController extends Controller
{
    private $userService;

    public function __construct(AccountService $accountService)
    {
        $this->accountService = $accountService;
    }

    public function getAccount($accountUid)
    {
        $user = auth()->user();
        $account = Account::where('owner_id', $user->id)
            ->where('uid', $accountUid)
            ->first();

        if (!$account) {
            throw new ApiHttpException(403, 'forbidden');
        }

        return response()->json(
            new AccountResource($account)
        );
    }

    public function updateContacts($accountUid, AccountContactsRequest $request)
    {
        $user = auth()->user();
        $account = Account::where('owner_id', $user->id)
            ->where('uid', $accountUid)
            ->first();

        if (!$account) {
            throw new ApiHttpException(403, 'forbidden');
        }

        $contacts = $request->validated()['contactInfo'];

        $this->accountService->updateContacts($account, $contacts);
        return response()->json(
            ['success' => true]
        );
    }

    public function updateName($accountUid, AccountNameRequest $request)
    {
        $user = auth()->user();
        $account = Account::where('owner_id', $user->id)
            ->where('uid', $accountUid)
            ->first();

        if (!$account) {
            throw new ApiHttpException(403, 'forbidden');
        }

        $newName = $request->validated()['accountName'];

        $this->accountService->updateName($account, $newName);
        return response()->json(
            [
                'success' => true,
                'account' => new AccountResource($account)
            ]
        );
    }

    public function createSubscription(Request $request, $accountUid)
    {
        $user = auth()->user();
        $account = Account::where('owner_id', $user->id)
            ->where('uid', $accountUid)
            ->first();

        if (!$account) {
            throw new ApiHttpException(403, 'forbidden');
        }

        $this->accountService->createSubscription($account, $request->input('token'));

        return response()->json([
            'success' => true,
            'account' => new AccountResource($account)
        ]);
    }
}
