import { Body, Controller, Delete, Get, Inject, Param, Post, Put, Request, UseGuards } from '@nestjs/common';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { AuthGuard } from 'src/jwt-auth/auth.guard';
import { Logger } from 'winston';

import { OptionalAuthGuard } from 'src/jwt-auth/optional-auth.guard';
import { BusinessListing } from '../models/db.model';
import { BusinessListingCriteria, JwtUser } from '../models/main.model';
import { BusinessListingService } from './business-listing.service';

@Controller('listings/business')
export class BusinessListingsController {
  constructor(
    private readonly listingsService: BusinessListingService,
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
  ) { }

  @UseGuards(AuthGuard)
  @Post('favorites/all')
  async findFavorites(@Request() req): Promise<any> {
    return await this.listingsService.findFavoriteListings(req.user as JwtUser);
  }

  @UseGuards(OptionalAuthGuard)
  @Get(':slugOrId')
  async findById(@Request() req, @Param('slugOrId') slugOrId: string): Promise<any> {
    // Support both slug (e.g., "restaurant-austin-tx-a3f7b2c1") and UUID
    return await this.listingsService.findBusinessBySlugOrId(slugOrId, req.user as JwtUser);
  }

  @UseGuards(OptionalAuthGuard)
  @Get('user/:userid')
  async findByUserId(@Request() req, @Param('userid') userid: string): Promise<BusinessListing[]> {
    return await this.listingsService.findBusinessesByEmail(userid, req.user as JwtUser);
  }

  @UseGuards(OptionalAuthGuard)
  @Post('find')
  async find(@Request() req, @Body() criteria: BusinessListingCriteria): Promise<any> {
    return await this.listingsService.searchBusinessListings(criteria, req.user as JwtUser);
  }
  @UseGuards(OptionalAuthGuard)
  @Post('findTotal')
  async findTotal(@Request() req, @Body() criteria: BusinessListingCriteria): Promise<number> {
    return await this.listingsService.getBusinessListingsCount(criteria, req.user as JwtUser);
  }

  @UseGuards(OptionalAuthGuard)
  @Post()
  async create(@Body() listing: any) {
    return await this.listingsService.createListing(listing);
  }

  @UseGuards(OptionalAuthGuard)
  @Put()
  async update(@Request() req, @Body() listing: any) {
    return await this.listingsService.updateBusinessListing(listing.id, listing, req.user as JwtUser);
  }

  @UseGuards(OptionalAuthGuard)
  @Delete('listing/:id')
  async deleteById(@Param('id') id: string) {
    await this.listingsService.deleteListing(id);
  }

  @UseGuards(AuthGuard)
  @Post('favorite/:id')
  async addFavorite(@Request() req, @Param('id') id: string) {
    await this.listingsService.addFavorite(id, req.user as JwtUser);
    return { success: true, message: 'Added to favorites' };
  }

  @UseGuards(AuthGuard)
  @Delete('favorite/:id')
  async deleteFavorite(@Request() req, @Param('id') id: string) {
    await this.listingsService.deleteFavorite(id, req.user as JwtUser);
    return { success: true, message: 'Removed from favorites' };
  }
}
