INSERT INTO `integrations` (`type`, `name`, `base_url`, `timeout_seconds`, `is_active`, `created_at`, `updated_at`)
SELECT 'fakturownia', 'Fakturownia', 'https://app.fakturownia.pl', 15, 1, NOW(), NOW()
WHERE NOT EXISTS (
    SELECT 1 FROM `integrations` WHERE `type` = 'fakturownia'
);

SET @fakturownia_integration_id := (
    SELECT `id`
    FROM (
        SELECT
            i.`id`,
            i.`is_active`,
            COALESCE(usage_counts.`used_count`, 0) AS `used_count`
        FROM `integrations` i
        LEFT JOIN (
            SELECT `integration_id`, COUNT(*) AS `used_count`
            FROM `invoice_configs`
            WHERE `integration_id` IS NOT NULL
            GROUP BY `integration_id`
        ) usage_counts ON usage_counts.`integration_id` = i.`id`
        WHERE i.`type` = 'fakturownia'
        ORDER BY i.`is_active` DESC, COALESCE(usage_counts.`used_count`, 0) DESC, i.`id` ASC
        LIMIT 1
    ) selected_fakturownia
);

UPDATE `integrations`
SET `name` = CONCAT(`name`, ' #', `id`),
    `updated_at` = NOW()
WHERE `type` = 'fakturownia'
  AND `id` <> @fakturownia_integration_id
  AND `name` = 'Fakturownia';

UPDATE `integrations`
SET `name` = 'Fakturownia',
    `base_url` = 'https://app.fakturownia.pl',
    `timeout_seconds` = 15,
    `updated_at` = NOW()
WHERE `id` = @fakturownia_integration_id
  AND `type` = 'fakturownia';

UPDATE `invoice_configs`
SET `integration_id` = @fakturownia_integration_id,
    `updated_at` = NOW()
WHERE `is_delegated` = 1;

UPDATE `invoice_configs`
SET `integration_id` = NULL,
    `updated_at` = NOW()
WHERE `is_delegated` = 0;

DELETE FROM `fakturownia_integration_settings`
WHERE `integration_id` <> @fakturownia_integration_id;

INSERT INTO `fakturownia_integration_settings`
    (`id`, `integration_id`, `account_prefix`, `default_kind`, `default_payment_to_days`, `created_at`, `updated_at`)
SELECT 1, @fakturownia_integration_id, '', 'vat', 7, NOW(), NOW()
WHERE NOT EXISTS (
    SELECT 1
    FROM `fakturownia_integration_settings`
    WHERE `integration_id` = @fakturownia_integration_id
);

UPDATE `fakturownia_integration_settings`
SET `id` = 1,
    `integration_id` = @fakturownia_integration_id,
    `updated_at` = NOW()
WHERE `integration_id` = @fakturownia_integration_id;

DELETE FROM `integrations`
WHERE `type` = 'fakturownia'
  AND `id` <> @fakturownia_integration_id;

ALTER TABLE `fakturownia_integration_settings` AUTO_INCREMENT = 2;
