using Microsoft.EntityFrameworkCore.Migrations;

#nullable disable

namespace VigilCareClinicalAPI.Migrations
{
    /// <inheritdoc />
    public partial class AddMrnSequence : Migration
    {
        /// <inheritdoc />
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql(@"
                DO $$
                DECLARE
                    next_val bigint;
                BEGIN
                    SELECT COALESCE(MAX(
                        CASE WHEN mrn ~ '^MRN-[0-9]+$'
                             THEN CAST(SUBSTRING(mrn FROM 5) AS bigint)
                             ELSE 0
                        END
                    ), 0) + 1 INTO next_val FROM patients;

                    EXECUTE format('CREATE SEQUENCE mrn_seq START WITH %s INCREMENT BY 1', next_val);
                END $$;
            ");
        }

        /// <inheritdoc />
        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.Sql("DROP SEQUENCE IF EXISTS mrn_seq;");
        }
    }
}
