CREATE TABLE `cheque_events` (
	`id` int AUTO_INCREMENT NOT NULL,
	`chequeId` int NOT NULL,
	`actorUserId` int NOT NULL,
	`action` varchar(80) NOT NULL,
	`atUtcMs` bigint NOT NULL,
	`beforeJson` text,
	`afterJson` text NOT NULL,
	CONSTRAINT `cheque_events_id` PRIMARY KEY(`id`)
);
--> statement-breakpoint
CREATE TABLE `cheques` (
	`id` int AUTO_INCREMENT NOT NULL,
	`sourceType` enum('client','supplier','expense') NOT NULL,
	`sourceId` int NOT NULL,
	`direction` enum('incoming','outgoing') NOT NULL,
	`fingerprint` varchar(64) NOT NULL,
	`number` varchar(80) NOT NULL,
	`giver` varchar(160) NOT NULL,
	`drawer` varchar(160) NOT NULL,
	`beneficiary` varchar(160),
	`bank` varchar(160) NOT NULL,
	`depositBank` varchar(160),
	`amountCents` int NOT NULL,
	`operationDateUtcMs` bigint NOT NULL,
	`depositDateUtcMs` bigint,
	`dueDateUtcMs` bigint,
	`clearedDateUtcMs` bigint,
	`status` enum('held','deposited','cleared','rejected','cancelled') NOT NULL DEFAULT 'held',
	`notes` text,
	`version` int NOT NULL DEFAULT 1,
	`createdByUserId` int NOT NULL,
	`createdAt` timestamp NOT NULL DEFAULT (now()),
	`updatedAt` timestamp NOT NULL DEFAULT (now()) ON UPDATE CURRENT_TIMESTAMP,
	CONSTRAINT `cheques_id` PRIMARY KEY(`id`),
	CONSTRAINT `cheques_source_unique` UNIQUE(`sourceType`,`sourceId`),
	CONSTRAINT `cheques_fingerprint_unique` UNIQUE(`fingerprint`)
);
--> statement-breakpoint
ALTER TABLE `expenses` MODIFY COLUMN `method` enum('cash','card','bank','other','cheque') NOT NULL;--> statement-breakpoint
ALTER TABLE `payments` MODIFY COLUMN `method` enum('cash','card','bank','other','cheque') NOT NULL DEFAULT 'bank';--> statement-breakpoint
ALTER TABLE `supplier_payments` MODIFY COLUMN `method` enum('cash','card','bank','other','cheque') NOT NULL DEFAULT 'bank';--> statement-breakpoint
CREATE INDEX `cheque_events_cheque_index` ON `cheque_events` (`chequeId`);--> statement-breakpoint
CREATE INDEX `cheques_number_index` ON `cheques` (`number`);--> statement-breakpoint
CREATE INDEX `cheques_deposit_date_index` ON `cheques` (`depositDateUtcMs`);--> statement-breakpoint
CREATE INDEX `cheques_status_index` ON `cheques` (`status`);