<?php

namespace App\Repositories;

use App\Models\PriceList;
use App\Models\Product;
use App\Traits\RepositoryRelationshipsTraits;

class PriceListRepository implements PriceListRepositoryInterface
{
    use RepositoryRelationshipsTraits;

    private string $Model;

    /**
     * @var array|string[]
     */
    private array $defaultRelations = ['Supplier'];

    /**
     * PriceListRepository constructor.
     */
    public function __construct()
    {
        $this->Model = PriceList::class;
        $this->actualRelations = $this->defaultRelations;
    }

    /**
     * Get's a record by it's ID
     *
     * @param int
     */
    public function get($id)
    {
        return $this->Model::find($id);
    }

    /**
     * Get's all records.
     *
     * @return mixed
     */
    public function all()
    {
        return $this->Model::all();
    }

    /**
     * Deletes a record.
     *
     * @param int
     */
    public function delete($id)
    {
        return $this->Model::destroy($id);
    }

    /**
     * Updates a post.
     *
     * @param int
     * @param array
     */
    public function update($id, array $data): bool
    {
        return $this->Model::find($id)->update($data);
    }

    /**
     * create new Record
     *
     * @param array
     */
    public function add($data): ?int
    {
        $obj = new PriceList;
        $obj->canSee = true;
        $obj->status == \App\Enums\DbStatusFieldEnum::draft;
        $obj->fill($data);
        $obj->save();

        return $obj->id;
    }

    public function attachProduct(int $productId, $price, int $priceListId)
    {
        /** @var PriceList $priceList */
        $priceList = $this->Model::find($priceListId);

        return $priceList->products()->attach($productId, ['price' => $price]);
    }

    public function updateProductPrice(int $productId, $price, int $priceListId)
    {
        /** @var PriceList $priceList */
        $priceList = $this->Model::find($priceListId);

        return $priceList->products()->updateExistingPivot(Product::find($productId), ['price' => $price]);

    }
}
