<?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 1;
	}

	public function is_applied(): bool {
		global $wpdb;

		$issues_table = $wpdb->prefix . 'sitefort_issues';
		$ignored_table = $wpdb->prefix . 'sitefort_ignored_issues';
		$runs_table = $wpdb->prefix . 'sitefort_scan_runs';
		$instances_table = $wpdb->prefix . 'sitefort_issue_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' ] );
	}

	public function apply(): bool {
		IssueRepository::ensure_tables();
		return true;
	}
}
