import type { Kysely } from "kysely";

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

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

    async list() {
        const rows = await this.db
            .selectFrom("default_emails")
            .selectAll()
            .orderBy("created_at", "asc")
            .execute();

        return rows.map((r: any) => ({
            id: r.id,
            email: r.email,
            updated_by: r.updated_by,
            created_at: r.created_at
        }));
    }

    async add(email: string, updated_by?: string) {
        const existing = await this.list();
        if (existing.length >= 2) {
            throw new Error("Maximum 2 default emails allowed");
        }

        const normalizedEmail = email.trim().toLowerCase();
        if (!normalizedEmail) throw new Error("Email is required");

        return await this.db
            .insertInto("default_emails")
            .values({
                email: normalizedEmail,
                is_active: true,
                updated_by: updated_by || null
            })
            .onConflict(oc => oc.column("email").doNothing())
            .returningAll()
            .executeTakeFirst();
    }

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

    async getAllEmails(): Promise<string[]> {
        const rows = await this.db
            .selectFrom("default_emails")
            .select("email")
            .where("is_active", "=", true)
            .execute();

        return rows.map((r: any) => r.email as string);
    }
}
