CREATE TABLE `enterprises` (
	`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
	`name` text NOT NULL,
	`type` text NOT NULL,
	`owner_name` text NOT NULL,
	`mobile` text NOT NULL,
	`address` text
);
--> statement-breakpoint
CREATE TABLE `staff` (
	`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
	`name` text NOT NULL,
	`username` text NOT NULL,
	`email` text,
	`mobile` text,
	`added_on` text NOT NULL,
	`password` text NOT NULL,
	`is_password_reset_needed` integer DEFAULT true NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `staff_username_unique` ON `staff` (`username`);--> statement-breakpoint
CREATE TABLE `roles` (
	`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
	`name` text NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `roles_name_unique` ON `roles` (`name`);--> statement-breakpoint
CREATE TABLE `permissions` (
	`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
	`name` text NOT NULL
);
--> statement-breakpoint
CREATE UNIQUE INDEX `permissions_name_unique` ON `permissions` (`name`);--> statement-breakpoint
CREATE TABLE `role_permissions` (
	`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
	`role_id` integer NOT NULL,
	`permission_id` integer NOT NULL,
	FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`) ON UPDATE no action ON DELETE no action,
	FOREIGN KEY (`permission_id`) REFERENCES `permissions`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE TABLE `staff_roles` (
	`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
	`staff_id` integer NOT NULL,
	`role_id` integer NOT NULL,
	FOREIGN KEY (`staff_id`) REFERENCES `staff`(`id`) ON UPDATE no action ON DELETE no action,
	FOREIGN KEY (`role_id`) REFERENCES `roles`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
CREATE TABLE `enterprise_staff` (
	`id` integer PRIMARY KEY AUTOINCREMENT NOT NULL,
	`staff_id` integer NOT NULL,
	`enterprise_id` integer NOT NULL,
	FOREIGN KEY (`staff_id`) REFERENCES `staff`(`id`) ON UPDATE no action ON DELETE no action,
	FOREIGN KEY (`enterprise_id`) REFERENCES `enterprises`(`id`) ON UPDATE no action ON DELETE no action
);
--> statement-breakpoint
ALTER TABLE `storage_spaces` ADD `enterprise_id` integer REFERENCES enterprises(id);--> statement-breakpoint
CREATE INDEX `storage_spaces_enterprise_idx` ON `storage_spaces` (`enterprise_id`);--> statement-breakpoint
ALTER TABLE `distributors` ADD `enterprise_id` integer REFERENCES enterprises(id);--> statement-breakpoint
CREATE INDEX `distributors_enterprise_idx` ON `distributors` (`enterprise_id`);--> statement-breakpoint
ALTER TABLE `products` ADD `enterprise_id` integer REFERENCES enterprises(id);--> statement-breakpoint
CREATE INDEX `products_enterprise_idx` ON `products` (`enterprise_id`);--> statement-breakpoint
ALTER TABLE `stock_batches` ADD `enterprise_id` integer REFERENCES enterprises(id);--> statement-breakpoint
CREATE INDEX `stock_batches_enterprise_idx` ON `stock_batches` (`enterprise_id`);