import { Body, Controller, Delete, Get, Inject, Param, Post, Put, Request, UseGuards } from '@nestjs/common';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { Logger } from 'winston';
import { FileService } from '../file/file.service.js';
import { OptionalJwtAuthGuard } from '../jwt-auth/optional-jwt-auth.guard.js';
import { CommercialPropertyListing } from '../models/db.model';
import { CommercialPropertyListingCriteria, JwtUser } from '../models/main.model.js';
import { CommercialPropertyService } from './commercial-property.service.js';

@Controller('listings/commercialProperty')
export class CommercialPropertyListingsController {
  constructor(
    private readonly listingsService: CommercialPropertyService,
    private fileService: FileService,
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
  ) {}

  @UseGuards(OptionalJwtAuthGuard)
  @Get(':id')
  findById(@Request() req, @Param('id') id: string): any {
    return this.listingsService.findCommercialPropertiesById(id, req.user as JwtUser);
  }

  @UseGuards(OptionalJwtAuthGuard)
  @Get('user/:email')
  findByEmail(@Request() req, @Param('email') email: string): Promise<CommercialPropertyListing[]> {
    return this.listingsService.findCommercialPropertiesByEmail(email, req.user as JwtUser);
  }
  @UseGuards(OptionalJwtAuthGuard)
  @Post('find')
  async find(@Request() req, @Body() criteria: CommercialPropertyListingCriteria): Promise<any> {
    return await this.listingsService.searchCommercialProperties(criteria, req.user as JwtUser);
  }
  @Post('findTotal')
  findTotal(@Body() criteria: CommercialPropertyListingCriteria): Promise<number> {
    return this.listingsService.getCommercialPropertiesCount(criteria);
  }
  @Get('states/all')
  getStates(): any {
    return this.listingsService.getStates();
  }
  @Post()
  async create(@Body() listing: any) {
    this.logger.info(`Save Listing`);
    return await this.listingsService.createListing(listing);
  }
  @Put()
  async update(@Body() listing: any) {
    this.logger.info(`Save Listing`);
    return await this.listingsService.updateCommercialPropertyListing(listing.id, listing);
  }
  @Delete(':id/:imagePath')
  deleteById(@Param('id') id: string, @Param('imagePath') imagePath: string) {
    this.listingsService.deleteListing(id);
    this.fileService.deleteDirectoryIfExists(imagePath);
  }
}
