<?php

namespace FiloBlu\Refilo\Model\Redirects\ResourceModel;

use FiloBlu\Refilo\Model\Redirects\Interfaces\RedirectInterface;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
use Magento\Framework\Model\ResourceModel\Db\Context;

class Redirects extends AbstractDb
{
    /** @var string */
    const TABLE = 'filoblu_refilo_redirect';
    /**
     * @var ResourceConnection
     */
    protected $resourceConnection;

    public function __construct(
        Context $context,
        ResourceConnection $resourceConnection
    ) {
        parent::__construct($context);
        $this->resourceConnection = $resourceConnection;
    }

    public function save($object)
    {
        $connection = $this->resourceConnection->getConnection();
        $table = $connection->getTableName(self::TABLE);

        $data =
            [
                RedirectInterface::HOST => $object->getHost(),
                RedirectInterface::REQUEST_URL => $object->getRequestURL(),
                RedirectInterface::TARGET_URL => $object->getTargetUrl(),
                RedirectInterface::REDIRECT_CODE => $object->getRedirectCode()
            ];

        $connection->insert($table, $data);
        $object->setId($connection->lastInsertId($table));
    }

    protected function _construct()
    {
        $this->_init('filoblu_refilo_redirect', 'id');
    }
}
