<?php
/**
 * Copyright 2022 Adobe
 * All Rights Reserved.
 *
 * NOTICE: Adobe permits you to use, modify, and distribute this file in
 * accordance with the terms of the Adobe license agreement accompanying
 * it.
 */
namespace Sut\Domain\Compatibility\Analyzers\Db;

use Magento\Mray\MagentoApiIndex\Api\DbSchemaInfo;
use Sut\Domain\Compatibility\Analyzers\AnalyzerInterface;
use Sut\Domain\Issue\IssueFactory;
use Sut\Domain\MRay\DTO\Module;

class TableAnalyzer implements AnalyzerInterface
{
    private const USAGES = [
        'extended-core-table',
        'added-table'
    ];

    private const ISSUE_CODES = [
        'Table conflicts with core table name' => 7001,
        'Extended core table that does not exist' => 7002,
    ];

    /**
     * @var DbSchemaInfo
     */
    private $dbSchemaInfo;

    /**
     * @var IssueFactory
     */
    private $issueFactory;

    /**
     * @param IssueFactory $issueFactory
     * @param DbSchemaInfo $dbSchemaInfo
     */
    public function __construct(IssueFactory $issueFactory, DbSchemaInfo $dbSchemaInfo)
    {
        $this->issueFactory = $issueFactory;
        $this->dbSchemaInfo = $dbSchemaInfo;
    }

    /**
     * @inheritdoc
     */
    public function analyze(Module\Dependency $dependency, Module\DependencyUsage $usage, string $version): array
    {
        if ($dependency->getType() !== 'db') {
            return [];
        }

        if (!in_array($usage->getType(), self::USAGES)) {
            return [];
        }

        $tableName = $dependency->getRealName();

        if ($usage->getType() === 'added-table' && $this->dbSchemaInfo->getTable($tableName, $version) !== null) {
            return [$this->issueFactory->createIssue(
                self::ISSUE_CODES['Table conflicts with core table name'],
                [$tableName, $version],
                $usage->getPosition(),
                $usage->getFile()
            )];
        }

        if ($usage->getType() === 'extended-core-table'
            && $this->dbSchemaInfo->getTable($tableName, $version) === null
        ) {
            return [$this->issueFactory->createIssue(
                self::ISSUE_CODES['Extended core table that does not exist'],
                [$tableName, $version],
                $usage->getPosition(),
                $usage->getFile()
            )];
        }

        return [];
    }
}
