<?php

namespace App\Services;

use App\Models\Customer;
use App\Models\CustomerAddress;
use App\Models\Outlet;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;

class CustomerService {
    public function login($data, $ip)
    {
        $identifier = $data['identifier'];
        $throttleKey = Str::lower($identifier) . '|' . $ip;

        if (RateLimiter::tooManyAttempts($throttleKey, 6)) {
            $seconds = RateLimiter::availableIn($throttleKey);
            return [
                'error' => 'lockout',
                'seconds' => $seconds,
                'until' => now()->addSeconds($seconds)->toIso8601String(),
            ];
        }
        

        $loginField = filter_var($identifier, FILTER_VALIDATE_EMAIL) ? 'email' : 'phone_number';
        
        $customer = Customer::where($loginField, $identifier)->first();

        $storedHash = $customer->password;

        if (str_starts_with($storedHash, '$2a$')) {
            $storedHash = str_replace('$2a$', '$2y$', $storedHash);
        }

        if (!$customer || !Hash::check($data['password'], $storedHash)) {
            RateLimiter::hit($throttleKey, 3600);
            return ['error' => 'invalid_credentials'];
        }

        RateLimiter::clear($throttleKey);
        $customer->tokens()->delete();
        
        return [
            'token' => $customer->createToken('CustomerAuthToken')->plainTextToken,
            'customer' => $customer,
        ];   
    }

    public function register($data)
    {
        $tenantId = config('app.current_tenant_id');

        $outletId = Outlet::where('tenant_id', $tenantId)
        ->where('is_main_outlet', true)
        ->first()
        ->value('uuid');

        Customer::create([
            'uuid' => (string) Str::uuid7(),
            'tenant_id' => $tenantId,
            'outlet_id' => $outletId,
            'name' => $data['name'],
            'email' => $data['email'],
            'phone_number' => $data['phone_number'],
            'password' => Hash::make($data['password']),
            'source' => 'online'
        ]);
    }

    public function updateCustomer($data, $customerId)
    {
        $tenantId = config('app.current_tenant_id');

        $customer =  Customer::where('uuid', $customerId)
        ->where('tenant_id', $tenantId)
        ->first();

        $customer->update([
            'name' => $data['name'],
        ]);

        return [
            'name'         => $customer->name,
            'email'        => $customer->email,
            'phone_number' => $customer->phone_number,
        ];
    }

    public function updatePassword($data, $customerId)
    {
        $tenantId = config('app.current_tenant_id');

        $customer =  Customer::where('uuid', $customerId)
        ->where('tenant_id', $tenantId)
        ->first();

        if(!Hash::check($data['old_password'], $customer->password)) {
            return ['error' => 'invalid old password'];
        }

        $customer->update([
            'password' => Hash::make($data['new_password'])
        ]);
    }

    public function getCustomerAddress($customerId)
    {
        $tenantId = config('app.current_tenant_id');

        $customerAddress = CustomerAddress::select([
        'uuid',
        'label',
        'full_address',
        'latitude',
        'longitude'
        ])
        ->where('customer_id', $customerId)
        ->where('tenant_id', $tenantId)
        ->get();

        return $customerAddress;
    }

    public function saveCustomerAddress($data, $customerId)
    {
        $tenantId = config('app.current_tenant_id');

        CustomerAddress::updateOrCreate([
            'uuid'        => $data['uuid'],
            'customer_id' => $customerId,
            'tenant_id'   => $tenantId
        ], [
            'label'        => $data['label'],
            'full_address' => $data['full_address'],
            'latitude'     => $data['latitude'],
            'longitude'    => $data['longitude']
        ]);
    }

    public function deleteCustomerAddress(string $customerId, string $id)
    {        
        CustomerAddress::where('uuid', $id)
        ->where('customer_id', $customerId)
        ->delete();
    }
}