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

@Controller()
@UseGuards(JwtAuthGuard)
export class StockTransactionsController {
  constructor(private readonly svc: StockTransactionsService) {}

  // ── Stock In ──────────────────────────────────────────────────────────────

  @Post("stock-in")
  createStockIn(
    @Body()
    body: {
      warehouseId: string;
      itemId: string;
      batchNumber: string;
      expiryDate: string;
      quantityMt: number;
      supplierName?: string;
      supplierTrn?: string;
      documentNumber?: string;
      documentDate?: string;
      referenceNumber?: string;
      unit?: string;
      unitPrice?: number;
    },
    @Req() req: Request & { user: { name: string } },
  ) {
    return this.svc.createStockIn({ ...body, submittedBy: req.user.name });
  }

  // ── Stock Out ─────────────────────────────────────────────────────────────

  @Post("stock-out")
  createStockOut(
    @Body()
      body: {
        warehouseId: string;
        itemId: string;
        batchId?: string; // Optional
        expiryDate?: string; // Optional selected expiry when batch number has multiple expiries
        quantityMt: number;
      },
    @Req() req: Request & { user: { name: string } },
  ) {
    return this.svc.createStockOut({ ...body, submittedBy: req.user.name });
  }

  // ── Pending approvals ─────────────────────────────────────────────────────

  @Get("stock-transactions/pending")
  findPending() {
    return this.svc.findPending();
  }

  @Get("stock-transactions")
  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,
    });
  }

  // ── Approve / Reject ──────────────────────────────────────────────────────

  @Post("stock-transactions/: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 transactions");
    }
    return this.svc.approve(id, req.user.name);
  }

  @Post("stock-transactions/: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 transactions");
    }
    return this.svc.reject(id, req.user.name, body.reason ?? "");
  }
}
