"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CustomerService = void 0;
const common_1 = require("@nestjs/common");
const prisma_query_builder_1 = require("../commons/utils/prisma-query-builder");
const storage_service_1 = require("../storage/storage.service");
const bootstrap_table_response_dto_1 = require("../commons/dto/bootstrap-table-response.dto");
const prisma_service_1 = require("../prisma/prisma.service");
let CustomerService = class CustomerService {
    constructor(prisma, storage) {
        this.prisma = prisma;
        this.storage = storage;
    }
    async create(dto) {
        const prefix = dto.fullName
            .replace(/[^a-zA-Z]/g, '')
            .toUpperCase()
            .slice(0, 3)
            .padEnd(3, 'X');
        const count = await this.prisma.customer.count();
        const number = String(count + 1).padStart(3, '0');
        const code = `${prefix}${number}`;
        let ktpPhotoUrl = undefined;
        if (dto.ktpPhotoTempId) {
            const temp = await this.prisma.tempPhoto.findUniqueOrThrow({
                where: { id: dto.ktpPhotoTempId },
            });
            ktpPhotoUrl = await this.storage.promoteToPermament(temp.url, `customers`);
            await this.prisma.tempPhoto.delete({ where: { id: temp.id } });
        }
        const { ktpPhotoTempId, ...customerData } = dto;
        return this.prisma.customer.create({
            data: {
                ...customerData,
                code,
                ktpPhotoUrl,
            },
        });
    }
    async findAll(query) {
        const allowedFilters = {
            code: 'string',
            fullName: 'string',
            phoneNumber: 'string',
            ktpNumber: 'string',
            address: 'string',
        };
        const where = (0, prisma_query_builder_1.buildWhereClause)(query, allowedFilters, ['code', 'fullName', 'phoneNumber', 'ktpNumber', 'address']);
        const allowedSortColumns = [
            'code',
            'fullName',
            'phoneNumber',
            'ktpNumber',
            'address',
            'createdAt',
        ];
        const orderBy = {};
        if (query.sort && allowedSortColumns.includes(query.sort)) {
            orderBy[query.sort] = query.sortOrder;
        }
        else {
            orderBy.createdAt = 'desc';
        }
        const [total, rows] = await this.prisma.$transaction([
            this.prisma.customer.count({ where }),
            this.prisma.customer.findMany({
                where,
                skip: query.skip,
                take: query.take,
                orderBy,
                include: {
                    _count: {
                        select: {
                            transactions: {
                                where: {
                                    status: 'COMPLETED'
                                }
                            }
                        }
                    },
                    transactions: {
                        select: {
                            totalAmount: true
                        },
                        where: {
                            status: 'COMPLETED'
                        }
                    }
                }
            }),
        ]);
        const formattedRows = rows.map(c => ({
            ...c,
            totalAmount: c.transactions.reduce((sum, t) => sum + Number(t.totalAmount ?? 0), 0),
            transactionCount: c._count.transactions,
            transactions: undefined
        }));
        return new bootstrap_table_response_dto_1.BootstrapTableResponseDto(total, formattedRows);
    }
    findOne(id) {
        return this.prisma.customer.findUnique({
            where: { id },
            include: {
                transactions: true,
            },
        });
    }
    async update(id, dto) {
        const existing = await this.prisma.customer.findUnique({ where: { id } });
        if (!existing) {
            throw new common_1.NotFoundException(`Customer with id ${id} not found`);
        }
        let ktpPhotoUrl = undefined;
        if (dto.ktpPhotoTempId) {
            const temp = await this.prisma.tempPhoto.findUnique({
                where: { id: dto.ktpPhotoTempId },
            });
            if (!temp) {
                throw new common_1.NotFoundException(`Temp photo not found. Please re-upload the image first.`);
            }
            if (existing.ktpPhotoUrl) {
                await this.storage.deleteFile(existing.ktpPhotoUrl);
            }
            ktpPhotoUrl = await this.storage.promoteToPermament(temp.url, `customers`);
            await this.prisma.tempPhoto.delete({ where: { id: temp.id } });
        }
        const { ktpPhotoTempId, ...customerData } = dto;
        return this.prisma.customer.update({
            where: { id },
            data: {
                ...customerData,
                ...(ktpPhotoUrl && { ktpPhotoUrl }),
            },
        });
    }
    async getCustomersForExport(query) {
        return this.prisma.customer.findMany({
            include: {
                _count: {
                    select: { transactions: true },
                },
            },
            orderBy: { createdAt: 'asc' },
        });
    }
    remove(id) {
        return this.prisma.customer.delete({
            where: { id },
        });
    }
};
exports.CustomerService = CustomerService;
exports.CustomerService = CustomerService = __decorate([
    (0, common_1.Injectable)(),
    __metadata("design:paramtypes", [prisma_service_1.PrismaService, storage_service_1.StorageService])
], CustomerService);
//# sourceMappingURL=customer.service.js.map