using System;
using System.Text.Json;
using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace Tiku.Infrastructure.Persistence.Migrations
{
    /// <inheritdoc />
    public partial class TrustedLearningCore : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<long>(
                name: "last_client_sequence",
                table: "practice_sessions",
                type: "bigint",
                nullable: false,
                defaultValue: 0L);

            migrationBuilder.AddColumn<string>(
                name: "status",
                table: "practice_sessions",
                type: "character varying(32)",
                maxLength: 32,
                nullable: false,
                defaultValue: "active");

            migrationBuilder.AddColumn<long>(
                name: "version",
                table: "practice_sessions",
                type: "bigint",
                nullable: false,
                defaultValue: 1L);

            migrationBuilder.AddColumn<bool>(
                name: "is_final",
                table: "practice_session_reports",
                type: "boolean",
                nullable: false,
                defaultValue: true);

            migrationBuilder.AddColumn<int>(
                name: "pending_review_count",
                table: "practice_session_reports",
                type: "integer",
                nullable: false,
                defaultValue: 0);

            migrationBuilder.AddColumn<int>(
                name: "scoring_version",
                table: "practice_session_reports",
                type: "integer",
                nullable: false,
                defaultValue: 1);

            migrationBuilder.AddColumn<string>(
                name: "status",
                table: "practice_session_reports",
                type: "character varying(32)",
                maxLength: 32,
                nullable: false,
                defaultValue: "final");

            migrationBuilder.AddColumn<int>(
                name: "version",
                table: "practice_session_reports",
                type: "integer",
                nullable: false,
                defaultValue: 1);

            migrationBuilder.AddColumn<string>(
                name: "answer_text_snapshot",
                table: "practice_session_questions",
                type: "text",
                nullable: true);

            migrationBuilder.AddColumn<string>(
                name: "content_snapshot",
                table: "practice_session_questions",
                type: "text",
                nullable: true);

            migrationBuilder.AddColumn<int>(
                name: "correct_option_index_snapshot",
                table: "practice_session_questions",
                type: "integer",
                nullable: true);

            migrationBuilder.AddColumn<JsonElement>(
                name: "correct_option_indices_snapshot",
                table: "practice_session_questions",
                type: "jsonb",
                nullable: false,
                defaultValueSql: "'[]'::jsonb");

            migrationBuilder.AddColumn<int>(
                name: "difficulty_snapshot",
                table: "practice_session_questions",
                type: "integer",
                nullable: true);

            migrationBuilder.AddColumn<string>(
                name: "explanation_snapshot",
                table: "practice_session_questions",
                type: "text",
                nullable: true);

            migrationBuilder.AddColumn<JsonElement>(
                name: "grading_rules_snapshot",
                table: "practice_session_questions",
                type: "jsonb",
                nullable: false,
                defaultValueSql: "'{}'::jsonb");

            migrationBuilder.AddColumn<JsonElement>(
                name: "options_snapshot",
                table: "practice_session_questions",
                type: "jsonb",
                nullable: false,
                defaultValueSql: "'[]'::jsonb");

            migrationBuilder.AddColumn<string>(
                name: "question_type",
                table: "practice_session_questions",
                type: "character varying(50)",
                maxLength: 50,
                nullable: false,
                defaultValue: "choice");

            migrationBuilder.AddColumn<int>(
                name: "snapshot_version",
                table: "practice_session_questions",
                type: "integer",
                nullable: false,
                defaultValue: 1);

            migrationBuilder.AddColumn<JsonElement>(
                name: "tags_snapshot",
                table: "practice_session_questions",
                type: "jsonb",
                nullable: false,
                defaultValueSql: "'[]'::jsonb");

            migrationBuilder.AddColumn<string>(
                name: "type_label_snapshot",
                table: "practice_session_questions",
                type: "character varying(100)",
                maxLength: 100,
                nullable: true);

            migrationBuilder.AddColumn<decimal>(
                name: "awarded_score",
                table: "answer_records",
                type: "numeric(8,2)",
                precision: 8,
                scale: 2,
                nullable: true);

            migrationBuilder.AddColumn<long>(
                name: "client_sequence",
                table: "answer_records",
                type: "bigint",
                nullable: false,
                defaultValue: 0L);

            migrationBuilder.AddColumn<string>(
                name: "grading_status",
                table: "answer_records",
                type: "character varying(32)",
                maxLength: 32,
                nullable: false,
                defaultValue: "pending_review");

            migrationBuilder.AddColumn<string>(
                name: "idempotency_key",
                table: "answer_records",
                type: "character varying(200)",
                maxLength: 200,
                nullable: false,
                defaultValue: "");

            migrationBuilder.AddColumn<bool>(
                name: "is_current",
                table: "answer_records",
                type: "boolean",
                nullable: false,
                defaultValue: true);

            migrationBuilder.AddColumn<string>(
                name: "request_hash",
                table: "answer_records",
                type: "character varying(64)",
                maxLength: 64,
                nullable: false,
                defaultValue: "");

            migrationBuilder.AddColumn<int>(
                name: "revision",
                table: "answer_records",
                type: "integer",
                nullable: false,
                defaultValue: 1);

            migrationBuilder.CreateTable(
                name: "learning_operation_idempotencies",
                columns: table => new
                {
                    id = table.Column<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
                    tenant_id = table.Column<Guid>(type: "uuid", nullable: false),
                    user_id = table.Column<Guid>(type: "uuid", nullable: false),
                    practice_session_id = table.Column<Guid>(type: "uuid", nullable: false),
                    operation_type = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
                    idempotency_key = table.Column<string>(type: "character varying(200)", maxLength: 200, nullable: false),
                    request_hash = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false),
                    response_snapshot = table.Column<JsonElement>(type: "jsonb", nullable: false, defaultValueSql: "'{}'::jsonb"),
                    created_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false, defaultValueSql: "now()"),
                    completed_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("pk_learning_operation_idempotencies", x => x.id);
                    table.UniqueConstraint("ak_learning_operation_idempotencies_tenant_id_id", x => new { x.tenant_id, x.id });
                    table.ForeignKey(
                        name: "fk_learning_operation_idempotencies_practice_sessions_tenant_i~",
                        columns: x => new { x.tenant_id, x.user_id, x.practice_session_id },
                        principalTable: "practice_sessions",
                        principalColumns: new[] { "tenant_id", "user_id", "id" },
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "fk_learning_operation_idempotencies_tenants_tenant_id",
                        column: x => x.tenant_id,
                        principalTable: "tenants",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "fk_learning_operation_idempotencies_users_user_id",
                        column: x => x.user_id,
                        principalTable: "users",
                        principalColumn: "id",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.Sql("""
                UPDATE practice_sessions
                SET status = CASE
                        WHEN finished_at IS NOT NULL THEN 'submitted'
                        WHEN expires_at IS NOT NULL AND expires_at <= now() THEN 'expired'
                        ELSE 'active'
                    END,
                    version = 1,
                    last_client_sequence = 0;

                UPDATE practice_session_reports
                SET status = 'legacy_unverified',
                    version = 1,
                    is_final = false,
                    pending_review_count = 0,
                    scoring_version = 0;

                UPDATE practice_session_questions AS session_question
                SET question_type = question.type,
                    type_label_snapshot = question.type_label,
                    difficulty_snapshot = question.difficulty,
                    tags_snapshot = question.tags,
                    content_snapshot = version.content,
                    options_snapshot = version.options,
                    correct_option_index_snapshot = version.correct_option_index,
                    correct_option_indices_snapshot = version.correct_option_indices,
                    answer_text_snapshot = version.answer_text,
                    explanation_snapshot = version.explanation,
                    grading_rules_snapshot = jsonb_build_object(
                        'version', 1,
                        'legacyBackfill', true),
                    snapshot_version = 1
                FROM questions AS question
                JOIN question_versions AS version
                  ON version.tenant_id = question.tenant_id
                 AND version.question_id = question.id
                WHERE question.tenant_id = session_question.question_owner_tenant_id
                  AND question.id = session_question.question_id
                  AND version.id = session_question.question_version_id;

                WITH ranked AS (
                    SELECT id,
                           row_number() OVER (
                               PARTITION BY tenant_id, user_id, practice_session_id
                               ORDER BY answered_at, created_at, id) AS client_sequence_value,
                           row_number() OVER (
                               PARTITION BY tenant_id, user_id, practice_session_id, session_question_id
                               ORDER BY answered_at, created_at, id) AS revision_value,
                           row_number() OVER (
                               PARTITION BY tenant_id, user_id, practice_session_id, session_question_id
                               ORDER BY answered_at DESC, created_at DESC, id DESC) AS current_rank
                    FROM answer_records
                )
                UPDATE answer_records AS answer
                SET client_sequence = ranked.client_sequence_value,
                    revision = ranked.revision_value,
                    is_current = ranked.current_rank = 1,
                    grading_status = 'legacy_unverified',
                    is_correct = NULL,
                    awarded_score = NULL,
                    idempotency_key = 'legacy-' || answer.id::text,
                    request_hash = repeat('0', 64)
                FROM ranked
                WHERE ranked.id = answer.id;

                UPDATE practice_sessions AS session
                SET last_client_sequence = sequence.maximum
                FROM (
                    SELECT tenant_id, user_id, practice_session_id, max(client_sequence) AS maximum
                    FROM answer_records
                    GROUP BY tenant_id, user_id, practice_session_id
                ) AS sequence
                WHERE sequence.tenant_id = session.tenant_id
                  AND sequence.user_id = session.user_id
                  AND sequence.practice_session_id = session.id;
                """);

            migrationBuilder.CreateIndex(
                name: "ix_practice_sessions_tenant_id_user_id_status_started_at",
                table: "practice_sessions",
                columns: new[] { "tenant_id", "user_id", "status", "started_at" });

            migrationBuilder.CreateIndex(
                name: "ix_answer_records_tenant_id_user_id_practice_session_id_client~",
                table: "answer_records",
                columns: new[] { "tenant_id", "user_id", "practice_session_id", "client_sequence" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "ux_answer_records_current_session_question",
                table: "answer_records",
                columns: new[] { "tenant_id", "user_id", "practice_session_id", "session_question_id" },
                unique: true,
                filter: "is_current");

            migrationBuilder.CreateIndex(
                name: "ux_answer_records_session_question_revision",
                table: "answer_records",
                columns: new[] { "tenant_id", "user_id", "practice_session_id", "session_question_id", "revision" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "ix_learning_operation_idempotencies_tenant_id_user_id_practice~",
                table: "learning_operation_idempotencies",
                columns: new[] { "tenant_id", "user_id", "practice_session_id", "operation_type", "idempotency_key" },
                unique: true);

            migrationBuilder.CreateIndex(
                name: "ix_learning_operation_idempotencies_user_id",
                table: "learning_operation_idempotencies",
                column: "user_id");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "learning_operation_idempotencies");

            migrationBuilder.DropIndex(
                name: "ix_practice_sessions_tenant_id_user_id_status_started_at",
                table: "practice_sessions");

            migrationBuilder.DropIndex(
                name: "ix_answer_records_tenant_id_user_id_practice_session_id_client~",
                table: "answer_records");

            migrationBuilder.DropIndex(
                name: "ux_answer_records_current_session_question",
                table: "answer_records");

            migrationBuilder.DropIndex(
                name: "ux_answer_records_session_question_revision",
                table: "answer_records");

            migrationBuilder.DropColumn(
                name: "last_client_sequence",
                table: "practice_sessions");

            migrationBuilder.DropColumn(
                name: "status",
                table: "practice_sessions");

            migrationBuilder.DropColumn(
                name: "version",
                table: "practice_sessions");

            migrationBuilder.DropColumn(
                name: "is_final",
                table: "practice_session_reports");

            migrationBuilder.DropColumn(
                name: "pending_review_count",
                table: "practice_session_reports");

            migrationBuilder.DropColumn(
                name: "scoring_version",
                table: "practice_session_reports");

            migrationBuilder.DropColumn(
                name: "status",
                table: "practice_session_reports");

            migrationBuilder.DropColumn(
                name: "version",
                table: "practice_session_reports");

            migrationBuilder.DropColumn(
                name: "answer_text_snapshot",
                table: "practice_session_questions");

            migrationBuilder.DropColumn(
                name: "content_snapshot",
                table: "practice_session_questions");

            migrationBuilder.DropColumn(
                name: "correct_option_index_snapshot",
                table: "practice_session_questions");

            migrationBuilder.DropColumn(
                name: "correct_option_indices_snapshot",
                table: "practice_session_questions");

            migrationBuilder.DropColumn(
                name: "difficulty_snapshot",
                table: "practice_session_questions");

            migrationBuilder.DropColumn(
                name: "explanation_snapshot",
                table: "practice_session_questions");

            migrationBuilder.DropColumn(
                name: "grading_rules_snapshot",
                table: "practice_session_questions");

            migrationBuilder.DropColumn(
                name: "options_snapshot",
                table: "practice_session_questions");

            migrationBuilder.DropColumn(
                name: "question_type",
                table: "practice_session_questions");

            migrationBuilder.DropColumn(
                name: "snapshot_version",
                table: "practice_session_questions");

            migrationBuilder.DropColumn(
                name: "tags_snapshot",
                table: "practice_session_questions");

            migrationBuilder.DropColumn(
                name: "type_label_snapshot",
                table: "practice_session_questions");

            migrationBuilder.DropColumn(
                name: "awarded_score",
                table: "answer_records");

            migrationBuilder.DropColumn(
                name: "client_sequence",
                table: "answer_records");

            migrationBuilder.DropColumn(
                name: "grading_status",
                table: "answer_records");

            migrationBuilder.DropColumn(
                name: "idempotency_key",
                table: "answer_records");

            migrationBuilder.DropColumn(
                name: "is_current",
                table: "answer_records");

            migrationBuilder.DropColumn(
                name: "request_hash",
                table: "answer_records");

            migrationBuilder.DropColumn(
                name: "revision",
                table: "answer_records");
        }
    }
}
