"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.ContactRepository = void 0;
const typeorm_1 = require("typeorm");
const ormconfig_1 = require("../ormconfig");
const ContactAggregate_1 = require("../../Domain/Contact/ContactAggregate");
const Logger_1 = require("../../Application/Services/Logger");
class ContactRepository {
    constructor() {
        this.repo = ormconfig_1.AppDataSource.getRepository(ContactAggregate_1.ContactAggregate);
    }
    async create(contact) {
        return this.repo.save(contact);
    }
    async findById(id) {
        return this.repo
            .createQueryBuilder('contact')
            .where('contact.id = :id', { id })
            .andWhere('contact.state != :softDelete', { softDelete: ContactAggregate_1.ContactState.SOFT_DELETE })
            .getOne();
    }
    async findByPage(from, to) {
        const startTime = performance.now();
        try {
            const limit = to - from + 1;
            const offset = from;
            // Get total count for pagination
            const totalCount = await this.repo.count({
                where: {
                    state: (0, typeorm_1.Not)(ContactAggregate_1.ContactState.SOFT_DELETE)
                }
            });
            // Get paginated results
            const contacts = await this.repo
                .createQueryBuilder('contact')
                .where('contact.state != :softDelete', { softDelete: ContactAggregate_1.ContactState.SOFT_DELETE })
                .orderBy('contact.createDate', 'DESC')
                .limit(limit)
                .offset(offset)
                .getMany();
            const endTime = performance.now();
            (0, Logger_1.logDatabase)('Contact page query completed', `executionTime: ${Math.round(endTime - startTime)}ms, found: ${contacts.length}, total: ${totalCount}, from: ${from}, to: ${to}`);
            return { contacts, totalCount };
        }
        catch (error) {
            const endTime = performance.now();
            (0, Logger_1.logDatabase)('Contact page query failed', `executionTime: ${Math.round(endTime - startTime)}ms, from: ${from}, to: ${to}`);
            (0, Logger_1.logError)('ContactRepository.findByPage error', error instanceof Error ? error : new Error(String(error)));
            throw new Error('Failed to get contacts page from database');
        }
    }
    async findByPageIncludingDeleted(from, to) {
        const startTime = performance.now();
        try {
            const limit = to - from + 1;
            const offset = from;
            // Get total count for pagination
            const totalCount = await this.repo.count();
            // Get paginated results
            const contacts = await this.repo
                .createQueryBuilder('contact')
                .orderBy('contact.createDate', 'DESC')
                .limit(limit)
                .offset(offset)
                .getMany();
            const endTime = performance.now();
            (0, Logger_1.logDatabase)('Contact page query completed (including deleted)', `executionTime: ${Math.round(endTime - startTime)}ms, found: ${contacts.length}, total: ${totalCount}, from: ${from}, to: ${to}`);
            return { contacts, totalCount };
        }
        catch (error) {
            const endTime = performance.now();
            (0, Logger_1.logDatabase)('Contact page query failed (including deleted)', `executionTime: ${Math.round(endTime - startTime)}ms, from: ${from}, to: ${to}`);
            (0, Logger_1.logError)('ContactRepository.findByPageIncludingDeleted error', error instanceof Error ? error : new Error(String(error)));
            throw new Error('Failed to get contacts page from database');
        }
    }
    async update(id, update) {
        await this.repo.update(id, update);
        return this.findById(id);
    }
    async delete(id) {
        return this.repo.delete(id);
    }
    async softDelete(id) {
        await this.repo.update(id, { state: ContactAggregate_1.ContactState.SOFT_DELETE });
        return this.findById(id);
    }
    async findByIdIncludingDeleted(id) {
        return this.repo.findOneBy({ id }); // Returns contact regardless of state
    }
    async searchIncludingDeleted(searchTerm) {
        return this.repo
            .createQueryBuilder('contact')
            .where('contact.name ILIKE :searchTerm', { searchTerm: `%${searchTerm}%` })
            .orWhere('contact.email ILIKE :searchTerm', { searchTerm: `%${searchTerm}%` })
            .orWhere('contact.txt ILIKE :searchTerm', { searchTerm: `%${searchTerm}%` })
            .getMany();
    }
    async search(searchTerm) {
        return this.repo
            .createQueryBuilder('contact')
            .where('contact.name ILIKE :searchTerm', { searchTerm: `%${searchTerm}%` })
            .orWhere('contact.email ILIKE :searchTerm', { searchTerm: `%${searchTerm}%` })
            .orWhere('contact.txt ILIKE :searchTerm', { searchTerm: `%${searchTerm}%` })
            .andWhere('contact.state != :softDelete', { softDelete: ContactAggregate_1.ContactState.SOFT_DELETE })
            .getMany();
    }
}
exports.ContactRepository = ContactRepository;
//# sourceMappingURL=ContactRepository.js.map