import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  Req,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { TrackingService } from './tracking.service';
import { CreateActivityDto } from './dto/create-activity.dto';
import { UpdateActivityDto } from './dto/update-activity.dto';
import { CreateBulkActivitiesDto } from './dto/create-bulk-activities.dto';
import { ActivityType } from '../../database/entities/activity.entity';

@Controller('api/v1/activities')
export class TrackingController {
  constructor(private readonly trackingService: TrackingService) {}

  @Post()
  async create(
    @Req() req: any,
    @Query('childId') childId: string,
    @Body() createActivityDto: CreateActivityDto,
  ) {
    if (!childId) {
      return {
        success: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: 'childId query parameter is required',
        },
      };
    }

    const activity = await this.trackingService.create(
      req.user.userId,
      childId,
      createActivityDto,
    );

    return {
      success: true,
      data: {
        activity,
      },
    };
  }

  @Post('bulk')
  @HttpCode(HttpStatus.CREATED)
  async createBulk(
    @Req() req: any,
    @Body() createBulkDto: CreateBulkActivitiesDto,
  ) {
    const activities = await this.trackingService.createBulkActivities(
      req.user.userId,
      createBulkDto,
    );

    return {
      success: true,
      data: {
        activities,
        count: activities.length,
        bulkOperationId: activities[0]?.bulkOperationId || null,
      },
    };
  }

  @Get()
  async findAll(
    @Req() req: any,
    @Query('childId') childId?: string,
    @Query('childIds') childIdsParam?: string,
    @Query('type') type?: string,
    @Query('startDate') startDate?: string,
    @Query('endDate') endDate?: string,
  ) {
    // Support both single childId and multiple childIds (comma-separated)
    let activities;

    if (childIdsParam) {
      // Multi-child query
      const childIds = childIdsParam.split(',').filter(id => id.trim());

      if (childIds.length === 0) {
        return {
          success: false,
          error: {
            code: 'VALIDATION_ERROR',
            message: 'At least one childId is required',
          },
        };
      }

      activities = await this.trackingService.getActivitiesForMultipleChildren(
        req.user.userId,
        childIds,
        type as ActivityType,
        startDate ? new Date(startDate) : undefined,
        endDate ? new Date(endDate) : undefined,
      );
    } else if (childId) {
      // Single child query (backward compatibility)
      activities = await this.trackingService.findAll(
        req.user.userId,
        childId,
        type,
        startDate,
        endDate,
      );
    } else {
      return {
        success: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: 'childId or childIds query parameter is required',
        },
      };
    }

    return {
      success: true,
      data: {
        activities,
      },
    };
  }

  @Get('daily-summary')
  async getDailySummary(
    @Req() req: any,
    @Query('childId') childId: string,
    @Query('date') date: string,
  ) {
    if (!childId) {
      return {
        success: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: 'childId query parameter is required',
        },
      };
    }

    if (!date) {
      return {
        success: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: 'date query parameter is required',
        },
      };
    }

    const summary = await this.trackingService.getDailySummary(
      req.user.userId,
      childId,
      date,
    );

    return {
      success: true,
      data: summary,
    };
  }

  @Get(':id')
  async findOne(@Req() req: any, @Param('id') id: string) {
    const activity = await this.trackingService.findOne(req.user.userId, id);

    return {
      success: true,
      data: {
        activity,
      },
    };
  }

  @Patch(':id')
  async update(
    @Req() req: any,
    @Param('id') id: string,
    @Body() updateActivityDto: UpdateActivityDto,
  ) {
    const activity = await this.trackingService.update(
      req.user.userId,
      id,
      updateActivityDto,
    );

    return {
      success: true,
      data: {
        activity,
      },
    };
  }

  @Delete(':id')
  @HttpCode(HttpStatus.OK)
  async remove(@Req() req: any, @Param('id') id: string) {
    await this.trackingService.remove(req.user.userId, id);

    return {
      success: true,
      message: 'Activity deleted successfully',
    };
  }
}
