<?php

namespace App\Services\Inventory;

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

class SupplyCategoryService
{
    public function list(): array
    {
        return SupplyCategory::query()->orderBy('name')->get()->toArray();
    }

    public function create(array $data): array
    {
        try {
            $category = SupplyCategory::query()->create([
                'name' => (string) ($data['name'] ?? ''),
            ]);
        } catch (\Throwable $e) {
            Log::error('Supply category create failed: ' . $e->getMessage());
            return ['ok' => false, 'message' => 'Failed to save category.'];
        }

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

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

        try {
            $category->update(['name' => (string) ($data['name'] ?? '')]);
        } catch (\Throwable $e) {
            Log::error('Supply category update failed: ' . $e->getMessage());
            return ['ok' => false, 'message' => 'Failed to update category.'];
        }

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

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

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

        return ['ok' => true];
    }
}
