using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace VigilCareClinicalAPI.Migrations
{
    /// <inheritdoc />
    public partial class AddAlertObservationCode : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.AddColumn<string>(
                name: "observation_code",
                table: "clinical_alerts",
                type: "character varying(50)",
                maxLength: 50,
                nullable: true);

            migrationBuilder.Sql(@"
                UPDATE clinical_alerts
                SET observation_code = CASE
                    WHEN details LIKE '%HEART_RATE%'  THEN 'HEART_RATE'
                    WHEN details LIKE '%RESP_RATE%'   THEN 'RESP_RATE'
                    WHEN details LIKE '%SYSTOLIC_BP%' THEN 'SYSTOLIC_BP'
                    WHEN details LIKE '%TEMP_C%'      THEN 'TEMP_C'
                    WHEN details LIKE '%SPO2%'        THEN 'SPO2'
                END
                WHERE alert_type = 'RAPID_DETERIORATION'
                  AND observation_code IS NULL;
            ");

            migrationBuilder.CreateIndex(
                name: "IX_clinical_alerts_encounter_id_alert_type_observation_code",
                table: "clinical_alerts",
                columns: new[] { "encounter_id", "alert_type", "observation_code" },
                filter: "status IN ('OPEN', 'ESCALATED')");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropIndex(
                name: "IX_clinical_alerts_encounter_id_alert_type_observation_code",
                table: "clinical_alerts");

            migrationBuilder.DropColumn(
                name: "observation_code",
                table: "clinical_alerts");
        }
    }
}
