import { MigrationInterface, QueryRunner } from "typeorm";

export class AddPaymentWebhookEventAndRefund1782000000001 implements MigrationInterface {
    name = "AddPaymentWebhookEventAndRefund1782000000001";

    public async up(queryRunner: QueryRunner): Promise<void> {
        // Enum for webhook provider — shares the same values as payments_method_enum
        // but is a separate type so both tables remain independently evolvable.
        await queryRunner.query(`
            CREATE TYPE freight.payment_webhook_method_enum AS ENUM ('telebirr', 'cbe-birr', 'ebirr');
        `);

        await queryRunner.query(`
            CREATE TABLE freight.payment_webhook_events (
                id                uuid         NOT NULL DEFAULT uuid_generate_v4(),
                provider          freight.payment_webhook_method_enum NOT NULL,
                external_event_id varchar(255) NOT NULL,
                merchant_order_id varchar(255),
                provider_txn_id   varchar(255),
                signature_valid   boolean      NOT NULL,
                status            varchar(100) NOT NULL,
                payload           jsonb        NOT NULL,
                received_at       TIMESTAMP    NOT NULL DEFAULT now(),
                processed_at      TIMESTAMP,
                processing_error  text,

                CONSTRAINT PK_payment_webhook_events PRIMARY KEY (id),
                CONSTRAINT UQ_payment_webhook_events_provider_event UNIQUE (provider, external_event_id)
            );
        `);

        await queryRunner.query(`
            CREATE INDEX IDX_payment_webhook_events_merchant_order_id
                ON freight.payment_webhook_events (merchant_order_id);
        `);

        await queryRunner.query(`
            CREATE TABLE freight.payment_refunds (
                id                 uuid         NOT NULL DEFAULT uuid_generate_v4(),
                payment_id         uuid         NOT NULL,
                amount_minor       int          NOT NULL,
                reason             varchar(255),
                provider_refund_id varchar(255),
                status             varchar(50)  NOT NULL,
                created_at         TIMESTAMP    NOT NULL DEFAULT now(),

                CONSTRAINT PK_payment_refunds PRIMARY KEY (id),
                CONSTRAINT FK_payment_refunds_payment
                    FOREIGN KEY (payment_id)
                    REFERENCES freight.payments (id)
                    ON DELETE RESTRICT
            );
        `);
    }

    public async down(queryRunner: QueryRunner): Promise<void> {
        await queryRunner.query(`DROP TABLE IF EXISTS freight.payment_refunds;`);
        await queryRunner.query(`DROP INDEX IF EXISTS freight.IDX_payment_webhook_events_merchant_order_id;`);
        await queryRunner.query(`DROP TABLE IF EXISTS freight.payment_webhook_events;`);
        await queryRunner.query(`DROP TYPE IF EXISTS freight.payment_webhook_method_enum;`);
    }
}
