<?php

namespace App\Services\Inventory;

use App\Models\Supplier;
use Illuminate\Support\Facades\Log;

class SupplierService
{
    public function list(array $filters = [], int $perPage = 20): array
    {
        $q = trim((string) ($filters['q'] ?? ''));
        $query = Supplier::query();
        if ($q !== '') {
            $query->where(function ($builder) use ($q) {
                $builder->where('name', 'like', '%' . $q . '%')
                    ->orWhere('email', 'like', '%' . $q . '%')
                    ->orWhere('phone', 'like', '%' . $q . '%');
            });
        }

        $paginator = $query->orderBy('name')->paginate($perPage);

        return [
            'items' => $paginator->items(),
            'pagination' => [
                'current_page' => $paginator->currentPage(),
                'per_page' => $paginator->perPage(),
                'total' => $paginator->total(),
                'total_pages' => $paginator->lastPage(),
            ],
        ];
    }

    public function create(array $data): array
    {
        try {
            $supplier = Supplier::query()->create($this->payload($data));
        } catch (\Throwable $e) {
            Log::error('Supplier create failed: ' . $e->getMessage());
            return ['ok' => false, 'message' => 'Failed to save supplier.'];
        }

        return ['ok' => true, 'supplier' => $supplier->toArray()];
    }

    public function update(int $id, array $data): array
    {
        $supplier = Supplier::query()->find($id);
        if (!$supplier) {
            return ['ok' => false, 'message' => 'Supplier not found.'];
        }

        try {
            $supplier->update($this->payload($data));
        } catch (\Throwable $e) {
            Log::error('Supplier update failed: ' . $e->getMessage());
            return ['ok' => false, 'message' => 'Failed to update supplier.'];
        }

        return ['ok' => true, 'supplier' => $supplier->toArray()];
    }

    public function delete(int $id): array
    {
        $supplier = Supplier::query()->find($id);
        if (!$supplier) {
            return ['ok' => false, 'message' => 'Supplier not found.'];
        }

        try {
            $supplier->delete();
        } catch (\Throwable $e) {
            Log::error('Supplier delete failed: ' . $e->getMessage());
            return ['ok' => false, 'message' => 'Failed to delete supplier.'];
        }

        return ['ok' => true];
    }

    private function payload(array $data): array
    {
        return [
            'name' => (string) ($data['name'] ?? ''),
            'email' => $data['email'] ?? null,
            'phone' => $data['phone'] ?? null,
            'address' => $data['address'] ?? null,
            'notes' => $data['notes'] ?? null,
        ];
    }
}
