import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Body,
  Param,
  Query,
  Req,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { FamiliesService } from './families.service';
import { InviteFamilyMemberDto } from './dto/invite-family-member.dto';
import { JoinFamilyDto } from './dto/join-family.dto';
import { FamilyRole } from '../../database/entities/family-member.entity';

@Controller('api/v1/families')
export class FamiliesController {
  constructor(private readonly familiesService: FamiliesService) {}

  @Post('invite')
  async inviteMember(
    @Req() req: any,
    @Query('familyId') familyId: string,
    @Body() inviteDto: InviteFamilyMemberDto,
  ) {
    if (!familyId) {
      return {
        success: false,
        error: {
          code: 'VALIDATION_ERROR',
          message: 'familyId query parameter is required',
        },
      };
    }

    const invitation = await this.familiesService.inviteMember(
      req.user.userId,
      familyId,
      inviteDto,
    );

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

  @Post('join')
  async joinFamily(@Req() req: any, @Body() joinDto: JoinFamilyDto) {
    const member = await this.familiesService.joinFamily(
      req.user.userId,
      joinDto,
    );

    return {
      success: true,
      data: {
        member,
        message: 'Successfully joined family',
      },
    };
  }

  @Get(':id')
  async getFamily(@Req() req: any, @Param('id') familyId: string) {
    const family = await this.familiesService.getFamily(
      req.user.userId,
      familyId,
    );

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

  @Get(':id/members')
  async getFamilyMembers(@Req() req: any, @Param('id') familyId: string) {
    const members = await this.familiesService.getFamilyMembers(
      req.user.userId,
      familyId,
    );

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

  @Patch(':id/members/:userId/role')
  async updateMemberRole(
    @Req() req: any,
    @Param('id') familyId: string,
    @Param('userId') targetUserId: string,
    @Body('role') role: string,
  ) {
    const member = await this.familiesService.updateMemberRole(
      req.user.userId,
      familyId,
      targetUserId,
      role as FamilyRole,
    );

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

  @Delete(':id/members/:userId')
  @HttpCode(HttpStatus.OK)
  async removeMember(
    @Req() req: any,
    @Param('id') familyId: string,
    @Param('userId') targetUserId: string,
  ) {
    await this.familiesService.removeMember(
      req.user.userId,
      familyId,
      targetUserId,
    );

    return {
      success: true,
      message: 'Member removed successfully',
    };
  }
}
