import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

export interface GiteaIssue {
  title: string;
  body: string;
  labels?: string[];
  assignees?: string[];
}

export interface GiteaResponse {
  id: number;
  number: number;
  title: string;
  state: string;
  html_url: string;
}

@Injectable({
  providedIn: 'root'
})
export class GiteaService {
  private giteaUrl = process.env['GITEA_URL'] || 'https://your-gitea-instance.com';
  private repoOwner = 'florale-emotion';
  private repoName = 'tickets';
  private apiToken = process.env['GITEA_TOKEN'] || '';

  constructor(private http: HttpClient) {}

  createIssue(issue: GiteaIssue): Observable<GiteaResponse> {
    const headers = new HttpHeaders({
      'Authorization': `token ${this.apiToken}`,
      'Content-Type': 'application/json'
    });

    const url = `${this.giteaUrl}/api/v1/repos/${this.repoOwner}/${this.repoName}/issues`;
    
    return this.http.post<GiteaResponse>(url, issue, { headers });
  }

  createTicketFromContact(formData: any): GiteaIssue {
    const eventTypeLabels: { [key: string]: string } = {
      'wedding': 'Hochzeit',
      'funeral': 'Beerdigung',
      'corporate': 'Corporate Event',
      'birthday': 'Geburtstag',
      'anniversary': 'Jubiläum',
      'other': 'Sonstiges'
    };

    const title = `Neue Anfrage: ${eventTypeLabels[formData.eventType] || formData.eventType} - ${formData.firstName} ${formData.lastName}`;
    
    const body = `
## Kundeninformationen
- **Name:** ${formData.firstName} ${formData.lastName}
- **E-Mail:** ${formData.email}
- **Telefon:** ${formData.phone || 'Nicht angegeben'}

## Event-Details
- **Art des Events:** ${eventTypeLabels[formData.eventType] || formData.eventType}
- **Gewünschtes Datum:** ${formData.eventDate || 'Nicht angegeben'}
- **Anzahl Gäste:** ${formData.guestCount || 'Nicht angegeben'}
- **Budget:** ${formData.budget || 'Nicht angegeben'}

## Nachricht
${formData.message}

---
*Automatisch erstellt am ${new Date().toLocaleString('de-DE')}*
    `.trim();

    return {
      title,
      body,
      labels: ['kunde-anfrage', eventTypeLabels[formData.eventType]?.toLowerCase() || 'sonstiges'],
      assignees: ['veronika', 'corinna']
    };
  }
}