import { MigrationInterface, QueryRunner, Table, TableUnique } from "typeorm";

export class CreateUserTable1661234567890 implements MigrationInterface {
    public async up(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.createTable(
            new Table({
                name: "user",
                columns: [
                    {
                        name: "id",
                        type: "uuid",
                        isPrimary: true,
                        isGenerated: true,
                        generationStrategy: "uuid",
                    },
                    {
                        name: "userName",
                        type: "varchar",
                        isNullable: false,
                    },
                    {
                        name: "email",
                        type: "varchar",
                        isNullable: false,
                    },
                    {
                        name: "password",
                        type: "varchar",
                        isNullable: false,
                    },
                    {
                        name: "firstName",
                        type: "varchar",
                        isNullable: true,
                    },
                    {
                        name: "lastName",
                        type: "varchar",
                        isNullable: true,
                    },
                    {
                        name: "role",
                        type: "varchar",
                        default: "'user'",
                    },
                    {
                        name: "createdAt",
                        type: "timestamp",
                        default: "now()",
                    },
                    {
                        name: "updatedAt",
                        type: "timestamp",
                        default: "now()",
                    },
                ],
            }),
            true
        );

        // Add a unique constraint on userName
        await queryRunner.createUniqueConstraint(
            "user",
            new TableUnique({
                columnNames: ["userName"],
                name: "UQ_user_userName",
            })
        );

        // Insert a default admin user - password is stored in shared/recipe-backend
        await queryRunner.query(
            `INSERT INTO "user" ("id", "userName", "email", "password", "role")
            VALUES (uuid_generate_v4(), $1, $2, $3, $4)`,
            ["admin", "anika@raemer.net", "$2b$12$zySMBXDcPF4VWpyvXluYwOS4pWJlED.peAvK9NEMewht6UQGw/8WK", "admin"]
        );
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        // Drop the unique constraint first
        await queryRunner.dropUniqueConstraint("user", "UQ_user_userName");
        // Drop the table
        await queryRunner.dropTable("user");
    }
}
