CREATE TABLE `ip_address` (
	`id` int unsigned AUTO_INCREMENT NOT NULL,
	`ip_address` int unsigned NOT NULL,
	`flags` tinyint unsigned NOT NULL,
	`listId` int unsigned,
	`created_at` datetime(6) NOT NULL DEFAULT current_timestamp(6),
	`updated_at` datetime(6) NOT NULL DEFAULT current_timestamp(6),
	CONSTRAINT `ip_address_id` PRIMARY KEY(`id`),
	CONSTRAINT `ip_address_idx` UNIQUE(`ip_address`)
);
--> statement-breakpoint
CREATE TABLE `ip_list` (
	`id` int unsigned AUTO_INCREMENT NOT NULL,
	`name` text NOT NULL,
	`url` text,
	`default_flags` tinyint unsigned NOT NULL,
	`created_at` datetime(6) NOT NULL DEFAULT current_timestamp(6),
	`updated_at` datetime(6) NOT NULL DEFAULT current_timestamp(6),
	CONSTRAINT `ip_list_id` PRIMARY KEY(`id`)
);
--> statement-breakpoint
CREATE TABLE `ip_address_user` (
	`id` int unsigned AUTO_INCREMENT NOT NULL,
	`userId` int,
	`ipAddressId` int unsigned,
	CONSTRAINT `ip_address_user_id` PRIMARY KEY(`id`)
);
--> statement-breakpoint
ALTER TABLE `audit_log` ADD `ipAddressId` int unsigned;--> statement-breakpoint
ALTER TABLE `ip_address` ADD CONSTRAINT `ip_address_listId_ip_list_id_fk` FOREIGN KEY (`listId`) REFERENCES `ip_list`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE `ip_address_user` ADD CONSTRAINT `ip_address_user_userId_user_id_fk` FOREIGN KEY (`userId`) REFERENCES `user`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
ALTER TABLE `ip_address_user` ADD CONSTRAINT `ip_address_user_ipAddressId_ip_address_id_fk` FOREIGN KEY (`ipAddressId`) REFERENCES `ip_address`(`id`) ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
CREATE INDEX `ip_flags_idx` ON `ip_address` (`flags`);--> statement-breakpoint
ALTER TABLE `audit_log` ADD CONSTRAINT `audit_log_ipAddressId_ip_address_id_fk` FOREIGN KEY (`ipAddressId`) REFERENCES `ip_address`(`id`) ON DELETE set null ON UPDATE no action;