<?php

namespace App\Modules\Inventory\Controllers;

use App\Http\Controllers\Controller;
use App\Http\Responses\ApiResponse;
use App\Modules\Inventory\Models\Supplier;
use App\Modules\Inventory\Requests\StoreSupplierRequest;
use App\Modules\Inventory\Requests\UpdateSupplierRequest;
use App\Modules\Inventory\Resources\SupplierResource;
use App\Modules\Tenant\Models\Company;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SupplierController extends Controller
{
    public function index(Request $request): JsonResponse
    {
        $company = $this->currentCompany($request);

        $suppliers = Supplier::query()
            ->where('company_id', $company->id)
            ->when($request->filled('search'), function ($query) use ($request): void {
                $search = $request->string('search')->toString();

                $query->where(function ($query) use ($search): void {
                    $query->where('name', 'like', "%{$search}%")
                        ->orWhere('email', 'like', "%{$search}%")
                        ->orWhere('phone', 'like', "%{$search}%");
                });
            })
            ->when($request->filled('status'), function ($query) use ($request): void {
                $query->where('status', $request->string('status')->toString());
            })
            ->orderBy('name')
            ->get();

        return ApiResponse::success(SupplierResource::collection($suppliers));
    }

    public function store(StoreSupplierRequest $request): JsonResponse
    {
        $company = $this->currentCompany($request);
        $data = $request->validated();

        $supplier = Supplier::query()->create([
            ...$data,
            'company_id' => $company->id,
            'status' => $data['status'] ?? 'active',
        ]);

        return ApiResponse::success(new SupplierResource($supplier), 'Supplier created successfully', 201);
    }

    public function update(UpdateSupplierRequest $request, Supplier $supplier): JsonResponse
    {
        $company = $this->currentCompany($request);

        if ((int) $supplier->company_id !== (int) $company->id) {
            return ApiResponse::error('Supplier not found', 404);
        }

        $supplier->update($request->validated());

        return ApiResponse::success(new SupplierResource($supplier), 'Supplier updated successfully');
    }

    private function currentCompany(Request $request): Company
    {
        return $request->attributes->get('currentCompany');
    }
}
