import {
    BadRequestException,
    ConflictException,
    Injectable,
    InternalServerErrorException,
    NotFoundException,
    Param,
} from "@nestjs/common";
import { PrismaService } from "../../prisma/prisma.service";

import { handlePrismaError } from "src/common/lib/handlePrismaError";
import { ConfigService } from "@nestjs/config";
import {
    formatNoDataResponse,
    formatPaginatedResponse,
    getPaginationOptions,
} from "src/common/lib/pagination-helper";
import { CylinderlogSelect } from "src/selects/cylinderlog";
import { CylinderMovement, Prisma } from "@prisma/client";

@Injectable()
export class CylinderClientService {
    constructor(
        private prisma: PrismaService,
        private readonly configService: ConfigService,
    ) { }

    async findAll(page: number, perPage: number, query?: string, clientId?: string) {

        try {
            const { skip, take } = getPaginationOptions({ page, perPage });

            // const where: any = {};
            // if (movement) {
            //     where.isCylinderAssigned = true;
            // }
            const where:any={}
            const sixMonthsAgo=new Date();
            sixMonthsAgo.setMonth(sixMonthsAgo.getMonth()-6);
            where.AND=[
                {isCylinderAssigned:true},
                {assignedAt:{lte:sixMonthsAgo}}
            ]
            const [items, total] = await this.prisma.$transaction([
                this.prisma.client_cylinders.findMany({
                    where,
                    include: {
                        cylinder: {
                            select: {
                                rfid: true,
                                item_id: true
                            },
                        },
                        client: {
                            select: {
                                address: true,
                                name: true
                            }
                        }
                    },
                    skip,
                    take,
                    orderBy: { assignedAt: "desc" },
                }),
                this.prisma.client_cylinders.count({ where }),
            ]);

            return formatPaginatedResponse(items, total, page, perPage);
        } catch (error) {
            handlePrismaError(error, "Fetching paginated Cylinder Logs");
        }
    }

    async searchCylinderClient(query: string, page: number, perPage: number) {
        
        try {
            const cleanedQuery = query?.trim();
            if (!cleanedQuery) throw new BadRequestException("Search query is required");

            const { skip, take } = getPaginationOptions({ page, perPage });

            const where = {
                OR: [
                    { cylinder: { is: { rfid: { contains: cleanedQuery } } } },
                    { cylinder: { is: { item_id: { contains: cleanedQuery } } } },
                ],
            };
            const [items, total] = await this.prisma.$transaction([
                this.prisma.client_cylinders.findMany({
                    where,
                    include: {
                        cylinder: {
                            select: { rfid: true, item_id: true },
                        },
                        client: {
                            select: { name: true, address: true },
                        },
                    },
                    skip,
                    take,
                    orderBy: { assignedAt: "desc" },
                }),
                this.prisma.client_cylinders.count({ where }),
            ]);
            if (total === 0) return formatNoDataResponse("No cylinders found.");
            return formatPaginatedResponse(items, total, page, perPage);
        } catch (error) {
            handlePrismaError(error, "Searching cylinder clients");
        }
    }
    // ...existing code...

}
