try {
}
catch {
} import { Injectable, UseGuards, BadRequestException } from '@nestjs/common';
import { CreateReaderDto } from './dto/create-reader.dto';
import { UpdateReaderDto } from './dto/update-reader.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { JwtAuthGuard } from 'src/auth/guards/jwt-auth.guard';
import { ReaderType } from '@prisma/client'
import { formatPaginatedResponse, getPaginationOptions } from 'src/common/lib/pagination-helper';
import { handlePrismaError } from 'src/common/lib/handlePrismaError';
import { read } from 'fs';

@Injectable()

export class ReaderService {
  constructor(private readonly prisma: PrismaService) { }
  async create(createReaderDto: CreateReaderDto) {
    try {
      const reader_id = createReaderDto.reader_id;
      const isPresent = await this.prisma.reader.findUnique(
        {
          where: { reader_id },
          select: { reader_id: true }
        }
      )
      if (!isPresent) {
        await this.prisma.reader.create({ data: createReaderDto })

        return 'Reader Created Successfully';
      }

    }
    catch {
      return "reader already exist"
    }

  }

  async findAll(page: number, perPage: number, search?: string, type?: string) {
    try {
      const { skip, take } = getPaginationOptions({ page, perPage });

      const where: any = {};

      if (search) {
        search = search.trim();
        where.OR = [
          { reader_id: { contains: search } },
        ];
      }

      if (type) {
        where.type = type;
      }

      const [items, total] = await this.prisma.$transaction([
        this.prisma.reader.findMany({
          where,
          select: {
            id: true,
            reader_id: true,
            status: true,
            type: true,
            lastSeen: true,
            createdAt: true,
            // warehouse:{select:{id:true,
            //   name:true
            // }}
          },
          skip,
          take,
          orderBy: { createdAt: "desc" },
        }),
        this.prisma.reader.count({ where }),
      ]);

      return formatPaginatedResponse(items, total, page, perPage);
    } catch (error) {
      console.log('error================', error)
      handlePrismaError(error, "Fetching paginated Reader");
    }
  }

  async findOne(id: string) {
    try {
      const reader = await this.prisma.reader.findUnique({
        where: { id },
      });

      if (!reader) {
        throw new Error('Reader not found');
      }

      return reader;
    } catch (error) {
      throw new Error(error.message || 'Failed to fetch reader');
    }
  }

  // reader.service.ts
  // async assignToWarehouse(reader_id: string, warehouse_id: string, type:ReaderType) {
  //   try {
  //     if (reader_id && warehouse_id) {
  //       const isReaderPresent = await this.prisma.reader.findUniqueOrThrow({
  //         where: { reader_id },
  //         select: { reader_id: true }
  //       })
  //       console.log("reader working")
  //       if (isReaderPresent) {
  //         const warehousePresent = await this.prisma.warehouse.findUnique({
  //           where: { id: warehouse_id },
  //           select: { id: true }
  //         })
  //         if (isReaderPresent) {
  //           await this.prisma.reader.update({
  //             where: { reader_id },
  //             data: { warehouse_id ,
  //               status:true,
  //               type:type
  //             },
  //           });
  //         }
  //       }
  //     }
  //   }
  //   catch {

  //   }
  //   return this.prisma.reader.update({
  //     where: { reader_id },
  //     data: {
  //       warehouse_id,
  //       status: true
  //     },
  //   });
  // }

  async findInReaders(readerIdToInclude?: string) {
    const whereConditions: any[] = [
      { status: false },

    ];

    if (readerIdToInclude) {
      whereConditions.push({ id: readerIdToInclude });
    }

    return this.prisma.reader.findMany({
      where: {
        OR: whereConditions,
      },
    });
  }



  async update(id: string, updateReaderDto: UpdateReaderDto) {
    try {
      const updatedReader = await this.prisma.reader.update({
        where: { id },
        data: updateReaderDto,
        select: {
          id: true,
          reader_id: true,
          status: true,
          type: true,
          createdAt: true,
        }
      });
      return updatedReader;
    } catch (error) {
      handlePrismaError(error, "Updating reader");
    }
  }

  async remove(id: string) {
    try {
      const linkedWarehouse = await this.prisma.warehouse.findFirst({
        where: { readerId: id }
      });

      if (linkedWarehouse) {
        throw new BadRequestException('Cannot delete reader as it is linked to a warehouse');
      }

      await this.prisma.reader.delete({
        where: { id }
      });
      return { message: 'Reader deleted successfully' };
    } catch (error) {
      if (error instanceof BadRequestException) {
        throw error;
      }
      handlePrismaError(error, "Deleting reader");
    }
  }
}
