<?php

namespace App\Http\Controllers\Api;

use App\Http\Resources\BootstrapResource;
use App\Models\Branch;
use App\Models\Category;
use App\Models\Currency;
use App\Models\ExpenseCategory;
use App\Models\PaymentMethod;
use App\Models\Role;
use App\Models\Shift;
use App\Models\TaxRate;
use App\Models\UnitOfMeasure;
use Illuminate\Http\Request;

class BootstrapController extends ApiController
{
    public function __invoke(Request $request): BootstrapResource
    {
        $user = $request->user()->loadMissing(['company', 'branch', 'role.permissions']);
        $companyId = $user->company_id;

        return new BootstrapResource([
            'user' => $user,
            'roles' => Role::all(),
            'branches' => Branch::query()->where('company_id', $companyId)->orderBy('name')->get(),
            'payment_methods' => PaymentMethod::query()->where('company_id', $companyId)->where('is_active', true)->orderBy('name')->get(),
            'tax_rates' => TaxRate::query()->where('company_id', $companyId)->where('is_active', true)->orderByDesc('is_default')->get(),
            'categories' => Category::query()->where('company_id', $companyId)->where('is_active', true)->orderBy('sort_order')->get(),
            'expense_categories' => ExpenseCategory::query()->where('company_id', $companyId)->orderBy('name')->get(),
            'units' => UnitOfMeasure::query()->where('company_id', $companyId)->orderBy('name')->get(),
            'currencies' => Currency::query()->where('is_active', true)->orderByDesc('is_base')->get(),
            'open_shift' => Shift::query()
                ->where('branch_id', $user->branch_id)
                ->where('user_id', $user->id)
                ->where('status', 'open')
                ->latest('opened_at')
                ->first(),
        ]);
    }
}
