<?php

namespace App\Services;

use App\Models\Address;
use Illuminate\Database\Eloquent\Collection;

class AddressService
{
    public function one($id): Address
    {
        return Address::find($id);
    }

    public function create(array $data): Address
    {
        return Address::create($data);
    }

    public function update(array $data, int $id): Address
    {
        $address = Address::findOrFail($id);

        if (data_get($data, 'is_primary') !== null && data_get($data, 'is_primary')) {
            Address::where('source', $address->source)
                ->where('source_id', $address->source_id)
                ->where('id', '!=', $id)
                ->update(['is_primary' => false]);
        }

        $address->fill($data);
        $address->save();

        return $address->fresh();
    }

    public function delete(int $id): bool
    {
        $address = Address::findOrFail($id);

        return $address->delete();
    }

    //

    public function findBySource(array $data): ?Collection
    {
        $allAddresses = Address::where('source', data_get($data, 'source'))
            ->where('source_id', data_get($data, 'source_id'))
            ->with(['city', 'state'])
            ->whereNull('deleted_at')
            ->orderBy('is_primary', 'desc')
            ->get();

        return $allAddresses;
    }

    public function findPrimaryBySource(array $data): ?Address
    {
        return Address::where('source', data_get($data, 'source'))
            ->where('source_id', data_get($data, 'source_id'))
            ->whereNull('deleted_at')
            ->orderBy('is_primary', 'desc')
            ->first();
    }
}
