import type { Kysely } from "kysely";
import { sql } from "kysely";

export class BlockedEmailRepository {
    private db: Kysely<any>;

    constructor(db: Kysely<any>) {
        this.db = db;
    }

    async list(limit: number = 50, offset: number = 0, search?: string) {
        let query = this.db.selectFrom("blocked_emails").selectAll().orderBy("created_at", "desc");
        let countQuery = this.db.selectFrom("blocked_emails").select(this.db.fn.count<number>("id").as("total"));

        if (search) {
            query = query.where("email", "ilike", `%${search}%`);
            countQuery = countQuery.where("email", "ilike", `%${search}%`);
        }

        const items = await query.limit(limit).offset(offset).execute();
        const countResult = await countQuery.executeTakeFirst();

        return { items, total: Number(countResult?.total || 0) };
    }

    async create(email: string, updated_by?: string) {
        return await this.db
            .insertInto("blocked_emails")
            .values({ email: email.toLowerCase().trim(), updated_by: updated_by || null })
            .returningAll()
            .executeTakeFirst();
    }

    async delete(id: string) {
        return await this.db.deleteFrom("blocked_emails").where("id", "=", id).execute();
    }

    async toggleActive(id: string, is_active: boolean, updated_by?: string) {
        return await this.db
            .updateTable("blocked_emails")
            .set({ is_active, updated_by: updated_by || null, updated_at: sql`now()` })
            .where("id", "=", id)
            .returningAll()
            .executeTakeFirst();
    }

    async getActiveEmails(): Promise<string[]> {
        const result = await this.db
            .selectFrom("blocked_emails")
            .select("email")
            .where("is_active", "=", true)
            .execute();
        return result.map((r: any) => r.email);
    }

    async getAllEmails(): Promise<string[]> {
        const result = await this.db.selectFrom("blocked_emails").select("email").execute();
        return result.map((r: any) => r.email);
    }
}
