import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  Query,
  Req,
} from '@nestjs/common';
import { MasterService } from './master.service';
import { CreateLookupDto, UpdateLookupDto } from './master.dto';
import { Request } from 'express';

@Controller('master')
export class MasterController {
  constructor(private readonly svc: MasterService) {}

  private sub(req: Request): string {
    return (req as any).tenantSubdomain as string;
  }

  @Post('seed')
  async seed(@Req() req: Request) {
    await this.svc.seed(this.sub(req));
    return { success: true, data: { seeded: true } };
  }

  @Get('types')
  async types(@Req() req: Request) {
    const types = await this.svc.types(this.sub(req));
    return { success: true, data: types };
  }

  @Get()
  async findAll(@Req() req: Request, @Query('type') type?: string) {
    const data = await this.svc.findAll(this.sub(req), type);
    return { success: true, data };
  }

  @Get(':type/list')
  async findByType(@Req() req: Request, @Param('type') type: string) {
    const data = await this.svc.findByType(this.sub(req), type);
    return { success: true, data };
  }

  @Get(':id')
  async findOne(@Req() req: Request, @Param('id') id: string) {
    const data = await this.svc.findOne(this.sub(req), id);
    return { success: true, data };
  }

  @Post()
  async create(@Req() req: Request, @Body() dto: CreateLookupDto) {
    const data = await this.svc.create(this.sub(req), dto);
    return { success: true, data };
  }

  @Put(':id')
  async update(@Req() req: Request, @Param('id') id: string, @Body() dto: UpdateLookupDto) {
    const data = await this.svc.update(this.sub(req), id, dto);
    return { success: true, data };
  }

  @Delete(':id')
  async remove(@Req() req: Request, @Param('id') id: string) {
    const data = await this.svc.remove(this.sub(req), id);
    return { success: true, data };
  }
}
