-- AlterEnum (User.role — member value used in JWT only; members live in members table)
ALTER TABLE `users` MODIFY `role` ENUM('owner', 'staff', 'trainer', 'member') NOT NULL;

-- AlterTable
ALTER TABLE `gyms` ADD COLUMN `member_portal_enabled` BOOLEAN NOT NULL DEFAULT false;

-- AlterTable
ALTER TABLE `members` ADD COLUMN `password_hash` VARCHAR(255) NULL,
    ADD COLUMN `portal_enabled` BOOLEAN NOT NULL DEFAULT false,
    ADD COLUMN `portal_activated_at` DATETIME(3) NULL,
    ADD COLUMN `portal_revoked_at` DATETIME(3) NULL,
    ADD COLUMN `portal_revoked_by_id` CHAR(36) NULL;

-- CreateIndex
CREATE INDEX `members_phone_portal_enabled_idx` ON `members`(`phone`, `portal_enabled`);

-- CreateTable
CREATE TABLE `member_invites` (
    `id` CHAR(36) NOT NULL,
    `member_id` CHAR(36) NOT NULL,
    `gym_id` CHAR(36) NOT NULL,
    `token_hash` VARCHAR(255) NOT NULL,
    `expires_at` DATETIME(3) NOT NULL,
    `used_at` DATETIME(3) NULL,
    `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),

    INDEX `member_invites_member_id_idx`(`member_id`),
    INDEX `member_invites_expires_at_idx`(`expires_at`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `member_refresh_tokens` (
    `id` CHAR(36) NOT NULL,
    `member_id` CHAR(36) NOT NULL,
    `token_hash` VARCHAR(255) NOT NULL,
    `expires_at` DATETIME(3) NOT NULL,
    `created_at` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),

    INDEX `member_refresh_tokens_member_id_idx`(`member_id`),
    INDEX `member_refresh_tokens_expires_at_idx`(`expires_at`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- AddForeignKey
ALTER TABLE `members` ADD CONSTRAINT `members_portal_revoked_by_id_fkey` FOREIGN KEY (`portal_revoked_by_id`) REFERENCES `users`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `member_invites` ADD CONSTRAINT `member_invites_member_id_fkey` FOREIGN KEY (`member_id`) REFERENCES `members`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `member_invites` ADD CONSTRAINT `member_invites_gym_id_fkey` FOREIGN KEY (`gym_id`) REFERENCES `gyms`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `member_refresh_tokens` ADD CONSTRAINT `member_refresh_tokens_member_id_fkey` FOREIGN KEY (`member_id`) REFERENCES `members`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;
