import {
  Controller,
  Get,
  Post,
  Delete,
  Param,
  Body,
  Query,
  Headers,
  UnauthorizedException,
  ParseIntPipe,
  DefaultValuePipe,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { SegmentRepository } from '../../../infrastructure/repositories/segment.repository';
import * as jwt from 'jsonwebtoken';

/**
 * Platform-admin Segment management endpoints.
 * Segments are pre-defined audience groups that can be used for BY_SEGMENT targeting.
 *
 * Platform admins manually or via ETL populate segment membership.
 * Common segments: trial_ending_soon, high_value, at_risk, new_users, etc.
 */
@Controller('api/v1/notifications/segments')
export class SegmentAdminController {
  constructor(private readonly repo: SegmentRepository) {}

  /** GET /api/v1/notifications/segments — list all segments with member counts */
  @Get()
  async listSegments(@Headers('authorization') auth: string) {
    this.requireAdmin(auth);
    return this.repo.listSegments();
  }

  /** GET /api/v1/notifications/segments/:key/members — paginated member list */
  @Get(':key/members')
  async getMembers(
    @Headers('authorization') auth: string,
    @Param('key') key: string,
    @Query('limit', new DefaultValuePipe(50), ParseIntPipe) limit: number,
    @Query('offset', new DefaultValuePipe(0), ParseIntPipe) offset: number,
  ) {
    this.requireAdmin(auth);
    return this.repo.getSegmentMembers(key, Math.min(limit, 500), offset);
  }

  /** POST /api/v1/notifications/segments/:key/sync — replace entire segment (bulk ETL) */
  @Post(':key/sync')
  async syncSegment(
    @Headers('authorization') auth: string,
    @Param('key') key: string,
    @Body() body: { tenantIds: string[] },
  ) {
    this.requireAdmin(auth);
    await this.repo.syncSegment(key, body.tenantIds ?? []);
    return { ok: true, count: body.tenantIds?.length ?? 0 };
  }

  /** POST /api/v1/notifications/segments/:key/add — add tenants to segment */
  @Post(':key/add')
  async addToSegment(
    @Headers('authorization') auth: string,
    @Param('key') key: string,
    @Body() body: { tenantIds: string[] },
  ) {
    this.requireAdmin(auth);
    await this.repo.addToSegment(key, body.tenantIds ?? []);
    return { ok: true };
  }

  /** POST /api/v1/notifications/segments/:key/remove — remove tenants from segment */
  @Post(':key/remove')
  async removeFromSegment(
    @Headers('authorization') auth: string,
    @Param('key') key: string,
    @Body() body: { tenantIds: string[] },
  ) {
    this.requireAdmin(auth);
    await this.repo.removeFromSegment(key, body.tenantIds ?? []);
    return { ok: true };
  }

  /** DELETE /api/v1/notifications/segments/:key — delete entire segment */
  @Delete(':key')
  @HttpCode(HttpStatus.NO_CONTENT)
  async deleteSegment(
    @Headers('authorization') auth: string,
    @Param('key') key: string,
  ) {
    this.requireAdmin(auth);
    await this.repo.deleteSegment(key);
  }

  private requireAdmin(auth: string): void {
    if (!auth?.startsWith('Bearer ')) throw new UnauthorizedException('Missing authorization header');
    const token = auth.slice(7);
    try {
      const payload = jwt.verify(token, process.env.JWT_SECRET || 'dev-secret') as any;
      const roles: string[] = Array.isArray(payload.roles) ? payload.roles : [];
      if (!roles.includes('platform_admin') && !roles.includes('platform_super_admin')) {
        throw new UnauthorizedException('Admin role required');
      }
    } catch (err) {
      if (err instanceof UnauthorizedException) throw err;
      throw new UnauthorizedException('Invalid JWT');
    }
  }
}
