<?php

declare(strict_types=1);

namespace SiteFort\Modules\Scanner\Migrations;

use SiteFort\Core\Database\Migration;
use SiteFort\Core\Database\SchemaInspector;
use SiteFort\Modules\Scanner\Repository\IssueRepository;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

final class IssueStoreSchemaV1 implements Migration {

	public function module_key(): string {
		return 'scanner_issue_store';
	}

	public function target_version(): int {
		return 4;
	}

	public function is_applied(): bool {
		if ( ! $this->has_required_structure() ) {
			return false;
		}

		foreach ( $this->tables() as $table ) {
			if ( ! SchemaInspector::table_engine_ready( $table ) ) {
				return false;
			}
		}

		return true;
	}

	public function apply(): bool {
		if ( ! $this->has_required_structure() ) {
			IssueRepository::ensure_tables();
		} else {
			foreach ( $this->tables() as $table ) {
				SchemaInspector::ensure_table_uses_innodb( $table );
			}
		}

		return $this->is_applied();
	}

	private function has_required_structure(): bool {
		$tables = $this->tables();
		$issues_table = $tables['issues'];
		$ignored_table = $tables['ignored'];
		$runs_table = $tables['runs'];
		$instances_table = $tables['instances'];

		if (
			! SchemaInspector::table_exists( $issues_table ) ||
			! SchemaInspector::table_exists( $ignored_table ) ||
			! SchemaInspector::table_exists( $runs_table ) ||
			! SchemaInspector::table_exists( $instances_table )
		) {
			return false;
		}

		if ( ! SchemaInspector::has_columns( $issues_table, [ 'resolved_at', 'first_seen_at', 'last_seen_at' ] ) ) {
			return false;
		}

		return SchemaInspector::has_columns( $instances_table, [ 'type', 'severity', 'status', 'file_path', 'message' ] );
	}

	/**
	 * @return array{issues:string,ignored:string,runs:string,instances:string}
	 */
	private function tables(): array {
		global $wpdb;

		return [
			'issues'    => $wpdb->prefix . 'sitefort_issues',
			'ignored'   => $wpdb->prefix . 'sitefort_ignored_issues',
			'runs'      => $wpdb->prefix . 'sitefort_scan_runs',
			'instances' => $wpdb->prefix . 'sitefort_issue_instances',
		];
	}
}
