<?php

namespace Modules\Inventory\Repositories;

use Modules\Core\Enums\StatusEnum;
use Modules\Inventory\DTO\InventorySettingFilter;
use Modules\Inventory\Models\Supplier;

class SupplierRepository
{
    public function all(InventorySettingFilter $filter, array $columns = ['*'], array $relations = [])
    {
        return Supplier::query()
            ->with($relations)
            ->select($columns)
            ->search($filter->search)
            ->when(
                $filter->status,
                fn($q, $status) => $q->where('status', $status)
            )
            ->orderByDesc('id')
            ->paginate($filter->perPage ?? 15);
    }

    public function find($id)
    {
        return Supplier::with('account')->findOrFail($id);
    }

    public function create(array $data)
    {
        $supplier = Supplier::create([
            'name'       => $data['name'],
            'phone'      => $data['phone'] ?? null,
            'address'    => $data['address'] ?? null,
            'account_id' => $data['account_id'],
            'status'     => $data['status'] ?? StatusEnum::ACTIVE,
        ]);

        return $supplier->fresh('account');
    }

    public function update(Supplier $supplier, array $data)
    {
        $supplier->update([
            'name'       => $data['name'],
            'phone'      => $data['phone'] ?? null,
            'address'    => $data['address'] ?? null,
            'account_id' => $data['account_id'] ?? $supplier->account_id,
            'status'     => $data['status'] ?? $supplier->status,
        ]);

        return $supplier->fresh('account');
    }

    public function updateStatus(Supplier $supplier, array $status)
    {
        $supplier->update([
            'status' => $status['status'] ?? StatusEnum::ACTIVE,
        ]);

        return $supplier;
    }
}
