import { PrintfulClient, ProductSyncer, WebflowClient, type ProductSyncerOptions } from "@blade-and-brawn/commerce";
import { env, log } from "../util";
import { db } from "../database/db";
import { DatabaseError } from "pg";
import type { Insertable, Selectable } from "kysely";
import type { ProductSyncs } from "../database/out/db";

type SyncStatus = "queued" | "active" | "failed" | "succeeded";

type QueuedProductSync = {
    id?: string,
    session: {
        name: string,
        id: string
    },
    filter: ProductSyncerOptions["filter"]
}

class AlreadyClaimedError extends Error { }

export class CommerceService {
    public readonly Printful = new PrintfulClient({
        token: env.PRINTFUL_AUTH,
        storeId: env.PRINTFUL_STORE_ID,
    });
    public readonly Webflow = new WebflowClient({
        siteId: env.WEBFLOW_SITE_ID,
        collectionsId: env.WEBFLOW_COLLECTION_ID,
        token: env.WEBFLOW_AUTH,
        webhookSecret: env.WEBFLOW_WEBHOOK_SECRET,
    });
    readonly Sync = new ProductSyncService(this.Printful, this.Webflow);
}

class ProductSyncService {
    readonly Queue = new ProductSyncQueueService();
    private readonly ProductSyncer: ProductSyncer;

    constructor(private readonly Printful: PrintfulClient, private readonly Webflow: WebflowClient) {
        this.ProductSyncer = new ProductSyncer(this.Printful, this.Webflow, log);
    }

    async start(queuedProductSync: QueuedProductSync) {
        let id = queuedProductSync.id ?? null;
        let freedSlot = false;
        try {
            log.info({ session: queuedProductSync.session }, "starting sync run");
            await this.ProductSyncer.run({
                filter: queuedProductSync.filter,
                onStart: async (startDate) => {
                    const values: Insertable<ProductSyncs> = {
                        session_id: queuedProductSync.session.id,
                        session_name: queuedProductSync.session.name,
                        started_at: startDate,
                        p_product_id_filter: queuedProductSync.filter?.pProductIds ?? null,
                    };
                    if (id) {
                        const result = await db.updateTable("product_syncs")
                            .set(values)
                            .where("id", "=", id)
                            .where("started_at", "is", null)
                            .executeTakeFirst();

                        // Guard against another worker/machine having already claimed
                        // this queued row between `queue.front()` and now.
                        if (result.numUpdatedRows === 0n) throw new AlreadyClaimedError();
                    }
                    else {
                        const result = await db.insertInto("product_syncs")
                            .values(values)
                            .returning("id")
                            .executeTakeFirstOrThrow();
                        id = result.id;
                    }
                },
                onStep: async (pProductIds: number[]) => {
                    if (!id) throw new Error("Expected sync run ID");
                    await db.updateTable("product_syncs")
                        .set({ syncing_p_product_ids: pProductIds })
                        .where("id", "=", id)
                        .execute();
                },
                onCompletion: async (completionDate, duration) => {
                    if (!id) throw new Error("Expected sync run ID");
                    await db.updateTable("product_syncs")
                        .set({ syncing_p_product_ids: [], ended_at: completionDate })
                        .where("id", "=", id)
                        .execute();
                    freedSlot = true;
                }
            });
        }
        catch (err) {
            if (err instanceof AlreadyClaimedError) {
                log.info("sync already claimed by another worker, skipping");
                return;
            }

            const activeSync = await this.getActive();

            const activeSyncConflict = activeSync && err instanceof DatabaseError && err.code === "23505";
            if (activeSyncConflict) {
                // If active sync has been syncing for 10 min (600000ms), clear it and retry this sync
                if (Date.now() - (activeSync.started_at?.getTime() ?? 0) > 600000) {
                    log.info("already active sync exceeded timeout");
                    await db.updateTable("product_syncs")
                        .set({ syncing_p_product_ids: [], ended_at: new Date(), has_failed: true })
                        .where("id", "=", activeSync.id)
                        .execute();
                    await this.start(queuedProductSync);
                }
                else {
                    log.info("sync already active, enqueuing next sync");
                    await this.Queue.enqueue(queuedProductSync);
                }
            }
            else {
                if (id) {
                    await db.updateTable("product_syncs")
                        .set({ syncing_p_product_ids: [], ended_at: new Date(), has_failed: true })
                        .where("id", "=", id)
                        .execute();
                    freedSlot = true;
                }
                throw err;
            }
        }
        finally {
            if (freedSlot) {
                try {
                    const frontQueuedSync = await this.Queue.front();
                    if (frontQueuedSync) await this.start(frontQueuedSync);
                }
                catch (err) {
                    log.error({ err }, "failed to process next queued sync")
                }
            }
        }
    }

    async getActive(sessionId?: string) {
        return await db.selectFrom("product_syncs")
            .selectAll()
            .$if(sessionId !== undefined, (qb) =>
                qb.where("session_id", "=", sessionId!)
            )
            .where("started_at", "is not", null)
            .where("ended_at", "is", null)
            .limit(1)
            .executeTakeFirst();
    }

    async getLatest(sessionId?: string) {
        return await db.selectFrom("product_syncs")
            .selectAll()
            .$if(sessionId !== undefined, (qb) =>
                qb.where("session_id", "=", sessionId!)
            )
            .orderBy("created_at", "desc")
            .limit(1)
            .executeTakeFirst();
    }

    deriveStatus(sync: Selectable<ProductSyncs>): SyncStatus {
        if (!sync.started_at) return "queued";
        if (!sync.ended_at) return "active";
        return sync.has_failed ? "failed" : "succeeded";
    }
}

class ProductSyncQueueService {
    async enqueue(queuedProductSync: QueuedProductSync) {
        const values: Insertable<ProductSyncs> = {
            session_id: queuedProductSync.session.id,
            session_name: queuedProductSync.session.name,
            p_product_id_filter: queuedProductSync.filter?.pProductIds ?? null
        };
        if (queuedProductSync.id) {
            await db.updateTable("product_syncs")
                .set(values)
                .where("id", "=", queuedProductSync.id)
                .execute();
        }
        else {
            await db.insertInto("product_syncs")
                .values(values)
                .execute();
        }
    }

    async front(): Promise<QueuedProductSync | undefined> {
        const result = await db.selectFrom("product_syncs")
            .selectAll()
            .where("started_at", "is", null)
            .orderBy("created_at", "asc")
            .limit(1)
            .executeTakeFirst();
        if (!result) return;

        return {
            id: result.id,
            session: {
                id: result.session_id,
                name: result.session_name
            },
            filter: {
                pProductIds: result.p_product_id_filter
            }
        }
    }
}
