import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { FormBuilder, FormGroup, Validators, FormArray } from '@angular/forms';
import { environment } from '@environments/environment';
import { Observable } from 'rxjs';

export interface Merchant {
  id?: string;
  name: string;
  logo?: string;
  description: string;
  address: string;
  phone: string;
  technicalContacts: TechnicalContact[];
  services: Service[];
  status: 'ACTIVE' | 'INACTIVE' | 'SUSPENDED';
}

export interface TechnicalContact {
  firstName: string;
  lastName: string;
  phone: string;
  email: string;
}

export interface Service {
  name: string;
  description: string;
  pricing: Pricing[];
}

export interface Pricing {
  name: string;
  type: 'Daily' | 'Weekly' | 'Monthly' | 'OneTime';
  amount: number;
  tax: number;
  currency: string;
  periodicity: 'Daily' | 'Weekly' | 'Monthly' | 'OneTime';
}

@Injectable({ providedIn: 'root' })
export class MerchantService {
  private http = inject(HttpClient);
  private fb = inject(FormBuilder);

  // Formulaires réactifs pour création/édition
  createMerchantForm(): FormGroup {
    return this.fb.group({
      name: ['', [Validators.required, Validators.minLength(2)]],
      logo: [''],
      description: ['', [Validators.required]],
      address: ['', [Validators.required]],
      phone: ['', [Validators.required, Validators.pattern(/^\+?[\d\s-]+$/)]],
      technicalContacts: this.fb.array([]),
      services: this.fb.array([]),
      status: ['ACTIVE']
    });
  }

  createTechnicalContactForm(): FormGroup {
    return this.fb.group({
      firstName: ['', Validators.required],
      lastName: ['', Validators.required],
      phone: ['', Validators.required],
      email: ['', [Validators.required, Validators.email]]
    });
  }

  createServiceForm(): FormGroup {
    return this.fb.group({
      name: ['', Validators.required],
      description: ['', Validators.required],
      pricing: this.fb.array([])
    });
  }

  createPricingForm(): FormGroup {
    return this.fb.group({
      name: ['', Validators.required],
      type: ['Daily', Validators.required],
      amount: [0, [Validators.required, Validators.min(0)]],
      tax: [0, [Validators.required, Validators.min(0)]],
      currency: ['XOF', Validators.required],
      periodicity: ['Daily', Validators.required]
    });
  }

  // Méthodes API
  getMerchants(): Observable<Merchant[]> {
    return this.http.get<Merchant[]>(`${environment.apiUrl}/merchants`);
  }

  createMerchant(merchant: Merchant): Observable<Merchant> {
    return this.http.post<Merchant>(`${environment.apiUrl}/merchants`, merchant);
  }

  updateMerchant(id: string, merchant: Merchant): Observable<Merchant> {
    return this.http.put<Merchant>(`${environment.apiUrl}/merchants/${id}`, merchant);
  }

  deleteMerchant(id: string): Observable<void> {
    return this.http.delete<void>(`${environment.apiUrl}/merchants/${id}`);
  }
}