import {
  BadRequestException,
  Body,
  Controller,
  Get,
  Param,
  Post,
  Query,
  Req,
  UseGuards,
} from "@nestjs/common";
import { JwtAuthGuard } from "./jwt-auth.guard";
import { RotationTransactionsService } from "./rotation-transactions.service";

@Controller("rotation-transactions")
@UseGuards(JwtAuthGuard)
export class RotationTransactionsController {
  constructor(private readonly svc: RotationTransactionsService) {}

  @Post()
  create(
    @Body()
    body: {
      warehouseId: string;
      vendorId: string;
      voucher: string;
      rotationIn: Array<{ itemId: string; batchNumber: string; expiryDate?: string; productionDate?: string; quantityMt: number }>;
      rotationOut: Array<{ itemId: string; batchId: string; quantityMt: number }>;
    },
    @Req() req: Request & { user: { name: string } },
  ) {
    return this.svc.create({ ...body, submittedBy: req.user.name });
  }

  @Get()
  findAll(@Query("status") status?: string, @Query("page") page?: string, @Query("limit") limit?: string) {
    return this.svc.findAll({
      status,
      page: page ? parseInt(page, 10) : undefined,
      limit: limit ? parseInt(limit, 10) : undefined,
    });
  }

  @Get(":id")
  findOne(@Param("id") id: string) {
    return this.svc.findOne(id);
  }

  @Post(":id/approve")
  approve(
    @Param("id") id: string,
    @Req() req: Request & { user: { name: string; role: string } },
  ) {
    if (req.user.role !== "store_manager" && req.user.role !== "super_admin") {
      throw new BadRequestException("Only store managers can approve rotations");
    }
    return this.svc.approve(id, req.user.name);
  }

  @Post(":id/reject")
  reject(
    @Param("id") id: string,
    @Body() body: { reason?: string },
    @Req() req: Request & { user: { name: string; role: string } },
  ) {
    if (req.user.role !== "store_manager" && req.user.role !== "super_admin") {
      throw new BadRequestException("Only store managers can reject rotations");
    }
    return this.svc.reject(id, req.user.name, body.reason ?? "");
  }
}
