<?php

declare(strict_types=1);

namespace SecurWP\Modules\Scanner\Migrations;

use SecurWP\Core\Database\Migration;
use SecurWP\Core\Database\SchemaInspector;
use SecurWP\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 . 'securwp_issues';
		$ignored_table = $wpdb->prefix . 'securwp_ignored_issues';
		$runs_table = $wpdb->prefix . 'securwp_scan_runs';
		$instances_table = $wpdb->prefix . 'securwp_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;
	}
}
