import {
  Controller, Get, Post, Delete, Patch, Param, Body, Headers, HttpCode, HttpStatus, NotFoundException,
} from '@nestjs/common';
import { PaymentRepository } from '../../../infrastructure/repositories/payment.repository';
import { PaymentMethod } from '../../../domain/entities/payment-method.entity';
import { PaymentProviderType } from '../../../domain/ports/payment-provider.port';

@Controller('api/v1/billing/payment-methods')
export class PaymentMethodController {
  constructor(private readonly paymentRepo: PaymentRepository) {}

  @Get()
  async listMethods(@Headers('x-tenant-id') tenantId: string) {
    const methods = await this.paymentRepo.findMethodsByTenantId(tenantId);
    return methods.map((m) => ({
      id: m.id,
      provider: m.provider,
      displayName: m.displayName,
      isDefault: m.isDefault,
      expiresAt: m.expiresAt,
      createdAt: m.createdAt,
    }));
  }

  @Post()
  async addMethod(
    @Headers('x-tenant-id') tenantId: string,
    @Body() body: { provider: PaymentProviderType; displayName: string; providerCustomerId?: string },
  ) {
    const method = new PaymentMethod();
    method.tenantId = tenantId;
    method.provider = body.provider;
    method.displayName = body.displayName;
    method.providerCustomerId = body.providerCustomerId ?? null;
    method.isDefault = false;

    const saved = await this.paymentRepo.saveMethod(method);
    return { id: saved.id, provider: saved.provider, displayName: saved.displayName };
  }

  @Patch(':id/default')
  @HttpCode(HttpStatus.OK)
  async setDefault(
    @Headers('x-tenant-id') tenantId: string,
    @Param('id') id: string,
  ) {
    const method = await this.paymentRepo.findMethodById(id);
    if (!method || method.tenantId !== tenantId) throw new NotFoundException('Payment method not found');

    await this.paymentRepo.clearDefaultMethods(tenantId);
    method.isDefault = true;
    await this.paymentRepo.saveMethod(method);
    return { success: true };
  }

  @Delete(':id')
  @HttpCode(HttpStatus.NO_CONTENT)
  async deleteMethod(
    @Headers('x-tenant-id') tenantId: string,
    @Param('id') id: string,
  ) {
    const method = await this.paymentRepo.findMethodById(id);
    if (!method || method.tenantId !== tenantId) throw new NotFoundException('Payment method not found');

    await this.paymentRepo.deleteMethod(id);
  }
}
