-- CreateTable
CREATE TABLE `CallSession` (
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `sessionId` VARCHAR(191) NOT NULL,
    `direction` VARCHAR(191) NOT NULL,
    `fromNumber` VARCHAR(191) NOT NULL,
    `toNumber` VARCHAR(191) NOT NULL,
    `type` VARCHAR(191) NULL,
    `status` VARCHAR(191) NOT NULL,
    `startTime` DATETIME(3) NOT NULL,
    `endTime` DATETIME(3) NULL,
    `duration` INTEGER NULL,
    `userId` INTEGER NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),
    `updatedAt` DATETIME(3) NOT NULL,

    UNIQUE INDEX `CallSession_sessionId_key`(`sessionId`),
    INDEX `CallSession_direction_idx`(`direction`),
    INDEX `CallSession_startTime_idx`(`startTime`),
    INDEX `CallSession_userId_idx`(`userId`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `CallLeg` (
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `callSid` VARCHAR(191) NOT NULL,
    `callSessionId` INTEGER NOT NULL,
    `fromNumber` VARCHAR(191) NOT NULL,
    `toNumber` VARCHAR(191) NOT NULL,
    `direction` VARCHAR(191) NULL,
    `status` VARCHAR(191) NOT NULL,
    `startTime` DATETIME(3) NOT NULL,
    `endTime` DATETIME(3) NULL,
    `userId` INTEGER NULL,
    `isTransfer` BOOLEAN NOT NULL DEFAULT false,
    `transferFrom` VARCHAR(191) NULL,
    `transferTo` VARCHAR(191) NULL,
    `transferType` VARCHAR(191) NULL,
    `recordingUrl` VARCHAR(191) NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),

    UNIQUE INDEX `CallLeg_callSid_key`(`callSid`),
    INDEX `CallLeg_callSessionId_idx`(`callSessionId`),
    INDEX `CallLeg_callSid_idx`(`callSid`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `AgentStatusHistory` (
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `userId` INTEGER NOT NULL,
    `status` VARCHAR(191) NOT NULL,
    `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),

    INDEX `AgentStatusHistory_userId_idx`(`userId`),
    INDEX `AgentStatusHistory_status_idx`(`status`),
    INDEX `AgentStatusHistory_createdAt_idx`(`createdAt`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- AddForeignKey
ALTER TABLE `CallSession` ADD CONSTRAINT `CallSession_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `CallLeg` ADD CONSTRAINT `CallLeg_callSessionId_fkey` FOREIGN KEY (`callSessionId`) REFERENCES `CallSession`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `CallLeg` ADD CONSTRAINT `CallLeg_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE `AgentStatusHistory` ADD CONSTRAINT `AgentStatusHistory_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;
