<?php

namespace App\Repositories\Auth;

use App\Models\User;
use App\Models\Client;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use App\Repositories\Interfaces\Auth\SocialAuthRepositoryInterface;
use Exception;
use Illuminate\Support\Facades\Log;

class SocialAuthRepository implements SocialAuthRepositoryInterface
{
    public function findOrCreateUserFromSocialite($user)
    {

        $auth_id = $user->id;
        $slug = 'flix-00' . time();

        $users = User::where('auth_id', $auth_id)->first();

        $client = Client::where('id', $users?->client_id)->first();

        if (!$client) {
            $data = [
                'slug' => $slug,
                'first_name' => $user->name ?? $user->nickname,
                'last_name' => '',
                'company_name' => 'flixoo',
                'webhook_verify_token' => Str::random(30),
                'api_key' => Str::random(30),
            ];
            Client::insert($data);
        }

        return User::firstOrCreate(
            [
                'email' => $user->email
            ],
            [
                'first_name' => $user->name ?? $user->nickname,
                'last_name' => '',
                'email' => $user->email,
                'username' => $user->nickname ?? '',
                'image' => json_encode(['original_image' => $user->avatar ?? '']),
                'status' => 1,
                'user_type' => 'user',
                'client_id' => Client::where('slug', $slug)->value('id'), // assign the client id here
                'password' => Hash::make(Str::random(16)),
            ]
        );
    }
}
