-- AlterTable
ALTER TABLE `company_settings` ADD COLUMN `issued_order_number_pattern` VARCHAR(100) NULL,
    ADD COLUMN `issued_order_type_code` VARCHAR(10) NULL;

-- CreateTable
CREATE TABLE `issued_orders` (
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `po_number` VARCHAR(50) NULL,
    `customer_id` INTEGER NULL,
    `status` ENUM('draft', 'sent', 'confirmed', 'completed', 'cancelled') NOT NULL DEFAULT 'draft',
    `currency` VARCHAR(10) NULL DEFAULT 'CZK',
    `vat_rate` DECIMAL(5, 2) NULL DEFAULT 21.00,
    `apply_vat` BOOLEAN NULL DEFAULT true,
    `exchange_rate` DECIMAL(10, 4) NULL DEFAULT 1.0000,
    `order_date` DATE NULL,
    `delivery_date` DATE NULL,
    `language` VARCHAR(5) NULL DEFAULT 'cs',
    `delivery_terms` VARCHAR(500) NULL,
    `payment_terms` VARCHAR(500) NULL,
    `issued_by` VARCHAR(255) NULL,
    `notes` TEXT NULL,
    `internal_notes` TEXT NULL,
    `created_at` DATETIME(0) NULL DEFAULT CURRENT_TIMESTAMP(0),
    `modified_at` DATETIME(0) NULL,

    UNIQUE INDEX `idx_issued_orders_number_unique`(`po_number`),
    INDEX `issued_orders_customer_id`(`customer_id`),
    INDEX `idx_issued_orders_status_date`(`status`, `order_date`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- CreateTable
CREATE TABLE `issued_order_items` (
    `id` INTEGER NOT NULL AUTO_INCREMENT,
    `issued_order_id` INTEGER NOT NULL,
    `description` VARCHAR(500) NULL,
    `item_description` TEXT NULL,
    `quantity` DECIMAL(12, 3) NULL DEFAULT 1.000,
    `unit` VARCHAR(20) NULL,
    `unit_price` DECIMAL(12, 2) NULL DEFAULT 0.00,
    `vat_rate` DECIMAL(5, 2) NULL DEFAULT 21.00,
    `position` INTEGER NULL DEFAULT 0,

    INDEX `issued_order_id`(`issued_order_id`),
    PRIMARY KEY (`id`)
) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

-- AddForeignKey
ALTER TABLE `issued_orders` ADD CONSTRAINT `issued_orders_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `customers`(`id`) ON DELETE RESTRICT ON UPDATE NO ACTION;

-- AddForeignKey
ALTER TABLE `issued_order_items` ADD CONSTRAINT `issued_order_items_ibfk_1` FOREIGN KEY (`issued_order_id`) REFERENCES `issued_orders`(`id`) ON DELETE CASCADE ON UPDATE NO ACTION;
