import {
    BadRequestException,
    Body,
    Controller,
    Get,
    Param,
    Post,
    Query,
    Req,
    UseGuards,
} from "@nestjs/common";
import { MaintenanceHistoryService } from "./maintenance-history.service";
import { AccountType } from "@prisma/client";
import { AccountTypesGuard } from "../../common/guards/accountTypes.guard";
import { AccountTypes } from "../../common/decorators/accountType.decorator";
import { CreateMaintenanceHistoryDto } from "./dto/create-maintenance-history.dto";

@Controller("maintenance-history")
export class MaintenanceHistoryController {
    constructor(
        private readonly maintenanceHistoryService: MaintenanceHistoryService,
    ) { }

    @Post()
    create(@Body() dto: CreateMaintenanceHistoryDto, @Req() req) {
        if (!dto.date) {
            throw new BadRequestException("Date is required");
        }
        return this.maintenanceHistoryService.create({
            ...dto,
            date: new Date(dto.date),
            dueDate: dto.dueDate ? new Date(dto.dueDate) : null,
            createdBy: req.user.sub,
            createdByName: req.user.name,
        });
    }

    @Get()
    async findAll(
        @Query('page') page: string = '1',
        @Query('per_page') perPage: string = '10',
        @Query('workType') workType?: string,
        @Query('q') query?: string,
        @Query('dateFrom') dateFrom?: string,
        @Query('dateTo') dateTo?: string,
        @Query('warehouseId') warehouseId?: string,
        @Req() req?: any,
    ) {
        return this.maintenanceHistoryService.findAll(
            parseInt(page),
            parseInt(perPage),
            workType,
            query,
            dateFrom,
            dateTo,
            warehouseId,
            req.user
        );
    }

    @Get("search")
    search(
        @Query("q") query: string,
        @Query("limit") limit?: string,
        @Query("page") page?: string
    ) {
        const pageNumber = parseInt(page ?? "1");
        const perPage = parseInt(limit ?? "10");
        return this.maintenanceHistoryService.search(query, pageNumber, perPage);
    }

    @Get("cylinder/:id")
    findAllByCylinder(
        @Param("id") id: string,
        @Query("limit") limit?: string,
        @Query("page") page?: string
    ) {
        const pageNumber = parseInt(page ?? "1");
        const perPage = parseInt(limit ?? "10");
        return this.maintenanceHistoryService.findAllByCylinder(id, pageNumber, perPage);
    }
}
