"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.postalCodesService = void 0;
const database_1 = require("../../../config/database");
exports.postalCodesService = {
    async upsert(data) {
        return database_1.prisma.postalCodeCache.upsert({
            where: { postalCode: data.postalCode },
            update: {
                city: data.city ?? undefined,
                province: data.province ?? undefined,
                centroidLat: data.centroidLat ?? undefined,
                centroidLng: data.centroidLng ?? undefined,
                lastUpdated: new Date(),
            },
            create: {
                postalCode: data.postalCode,
                city: data.city ?? null,
                province: data.province ?? null,
                centroidLat: data.centroidLat ?? null,
                centroidLng: data.centroidLng ?? null,
            },
        });
    },
    async findByPostalCode(code) {
        return database_1.prisma.postalCodeCache.findUnique({
            where: { postalCode: code },
        });
    },
    async findAll(filters) {
        const { page, limit, search } = filters;
        const skip = (page - 1) * limit;
        const where = {};
        if (search) {
            where.OR = [
                { postalCode: { contains: search, mode: 'insensitive' } },
                { city: { contains: search, mode: 'insensitive' } },
                { province: { contains: search, mode: 'insensitive' } },
            ];
        }
        const [items, total] = await Promise.all([
            database_1.prisma.postalCodeCache.findMany({
                where,
                skip,
                take: limit,
                orderBy: { lastUpdated: 'desc' },
            }),
            database_1.prisma.postalCodeCache.count({ where }),
        ]);
        return {
            postalCodes: items,
            pagination: { page, limit, total, totalPages: Math.ceil(total / limit) },
        };
    },
    async delete(code) {
        return database_1.prisma.postalCodeCache.delete({
            where: { postalCode: code },
        });
    },
};
//# sourceMappingURL=postal-codes.service.js.map