<?php

namespace App\Providers;

use App\Models\BadDebts\BadDebt;
use App\Models\Boards\Post;
use App\Models\Commons\Menu;
use App\Models\Members\User;
use App\Models\Orders\Client;
use App\Models\Orders\Order;
use App\Models\Tenants\Approval;
use App\Models\Tenants\ApprovalStep;
use App\Models\Tenants\Bill;
use App\Models\Tenants\Deposit;
use App\Models\Tenants\ExpectedExpense;
use App\Models\Tenants\Purchase;
use App\Models\Tenants\Sale;
use App\Models\Tenants\Stock;
use App\Models\Tenants\Tenant;
use App\Models\Tenants\Withdrawal;
use App\Observers\ExpenseSync\BillExpenseSyncObserver;
use App\Observers\ExpenseSync\PurchaseExpenseSyncObserver;
use App\Observers\ExpenseSync\WithdrawalExpenseSyncObserver;
use App\Observers\MenuObserver;
use App\Observers\StatEventObserver;
use App\Observers\TenantObserver;
use App\Observers\TodayIssue\ApprovalIssueObserver;
use App\Observers\TodayIssue\ApprovalStepIssueObserver;
use App\Observers\TodayIssue\BadDebtIssueObserver;
use App\Observers\TodayIssue\ClientIssueObserver;
use App\Observers\TodayIssue\DepositIssueObserver;
use App\Observers\TodayIssue\ExpectedExpenseIssueObserver;
use App\Observers\TodayIssue\OrderIssueObserver;
use App\Observers\TodayIssue\StockIssueObserver;
use App\Observers\TodayIssue\WithdrawalIssueObserver;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        // 개발환경 + API 라우트에서만 쿼리 로그 수집
        if (app()->environment('local') && !app()->runningInConsole()) {
            if (request()->is('api/*')) {
                DB::enableQueryLog();
            }
        }
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        // Morph Map: 다형성 관계 모델 등록 (enforceMorphMap 사용 시 필수)
        Relation::enforceMorphMap([
            'user' => User::class,
            'post' => Post::class,
        ]);

        // DB::enableQueryLog();
        Builder::macro('debug', function ($debug = null) {
            if (is_null($debug) && app()->environment('local')) {
                $debug = true;
            }
            if ($debug) {
                \DB::enableQueryLog();
            }

            return $this;
        });

        // 메뉴 생성/수정/삭제 ↔ 권한 자동 동기화
        Menu::observe(MenuObserver::class);

        // 테넌트 생성 시 자동 실행
        Tenant::observe(TenantObserver::class);

        // CEO 대시보드 오늘의 이슈 실시간 저장
        Order::observe(OrderIssueObserver::class);
        BadDebt::observe(BadDebtIssueObserver::class);
        Stock::observe(StockIssueObserver::class);
        ExpectedExpense::observe(ExpectedExpenseIssueObserver::class);
        ApprovalStep::observe(ApprovalStepIssueObserver::class);
        Approval::observe(ApprovalIssueObserver::class);
        Client::observe(ClientIssueObserver::class);
        Deposit::observe(DepositIssueObserver::class);
        Withdrawal::observe(WithdrawalIssueObserver::class);

        // 예상 지출 자동 동기화 (매입/카드결제/발행어음 → expected_expenses)
        Purchase::observe(PurchaseExpenseSyncObserver::class);
        Withdrawal::observe(WithdrawalExpenseSyncObserver::class);
        Bill::observe(BillExpenseSyncObserver::class);

        // 통계 이벤트 기록 (stat_events 테이블)
        Order::observe(StatEventObserver::class);
        Sale::observe(StatEventObserver::class);
        Deposit::observe(StatEventObserver::class);
        Withdrawal::observe(StatEventObserver::class);
        Purchase::observe(StatEventObserver::class);
        Approval::observe(StatEventObserver::class);
    }
}
