<?php

namespace App\Traits;
use App\Enums\StatusEnum;
use App\Models\Platform;
use App\Models\SocialAccount;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;


trait AccountManager
{

    /**
     * Save social account
     *
     * @param string $guard
     * @param Platform $platform
     * @param array $accountInfo
     * @param string $account_type
     * @return array
     */
    protected function saveAccount(string $guard, Platform $platform, array $accountInfo, string $account_type, string $is_official, int|string $dbId = null): array
    {

        $socialAccount = DB::transaction(function () use ($guard, $platform, $accountInfo, $account_type, $is_official, $dbId) {

            $user = auth_user($guard);
            $accountId = Arr::get($accountInfo, "account_id", null);

            $findBy = ['account_id' => $accountId, 'platform_id' => $platform->id];

            switch ($guard) {
                case 'web':
                    $findBy['user_id'] = $user->id;
                    break;
            }

            $account = $dbId ? SocialAccount::find($dbId) : SocialAccount::firstOrNew($findBy);
            $account->platform_id = $platform->id;
            $account->name = Arr::get($accountInfo, 'name');
            $account->account_information = $accountInfo;
            $account->status = StatusEnum::true->status();
            $account->is_connected = StatusEnum::true->status();
            $account->account_type = $account_type;
            $account->is_official = $is_official;

            $account->token = Arr::get($accountInfo, "token", null);
            $account->access_token_expire_at = Arr::get($accountInfo, "access_token_expire_at", null);
            $account->refresh_token = Arr::get($accountInfo, "refresh_token", null);
            $account->refresh_token_expire_at = Arr::get($accountInfo, "refresh_token_expire_at", null);
            $account->workspace_id = current_workspace()?->id;



            $account->user_id = $user->id;


            $account->save();

            return $account;

        });

        return [
            'status' => true,
            'account' => $socialAccount
        ];

    }






    public function disConnectAccount(SocialAccount $account): void
    {

        $account->is_connected = StatusEnum::false->status();
        $account->update();

    }

}
