<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class QueryOptimizationServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap services.
     */
    public function boot(): void
    {
        // Enable query logging in development
        if (config('app.debug') && config('optimization.database.query_log')) {
            DB::listen(function ($query) {
                $time = $query->time;
                $sql = $query->sql;
                $bindings = $query->bindings;
                
                // Log slow queries
                if ($time > config('optimization.database.slow_query_threshold', 2000)) {
                    Log::warning('Slow Query Detected', [
                        'time' => $time . 'ms',
                        'sql' => $sql,
                        'bindings' => $bindings
                    ]);
                }
            });
        }

        // Add global scopes for common optimizations
        $this->addGlobalScopes();
    }

    /**
     * Add global scopes for query optimization
     */
    private function addGlobalScopes(): void
    {
        // Add eager loading for common relationships
        Builder::macro('withCommonRelations', function () {
            return $this->when($this->getModel() instanceof \App\Models\Anggota, function ($query) {
                return $query->with([
                    'refJenjang:id,jenjang',
                    'refGrupUpa:id,nama_grup_upa',
                    'dpc:id,nama_dpc',
                    'dpd:id,nama_dpd'
                ]);
            });
        });

        // Add select optimization for list views
        Builder::macro('selectForList', function () {
            return $this->when($this->getModel() instanceof \App\Models\Anggota, function ($query) {
                return $query->select([
                    'id', 'nama_lengkap', 'jenis_kelamin', 'status_keanggotaan',
                    'ref_jenjang_id', 'ref_grup_upa_id', 'dpc_id', 'dpd_id',
                    'created_at', 'updated_at'
                ]);
            });
        });

        // Add caching for expensive calculations
        Builder::macro('remember', function ($key, $ttl = 3600, $callback = null) {
            if ($callback) {
                return cache()->remember($key, $ttl, $callback);
            }
            
            $query = $this;
            return cache()->remember($key, $ttl, function () use ($query) {
                return $query->get();
            });
        });
    }
}