import * as plugins from '../plugins.ts';
import type * as interfaces from '../../ts_interfaces/index.ts';
import { BaseProvider, type ITestConnectionResult, type IListOptions } from './classes.baseprovider.ts';

/**
 * GitLab API v4 provider implementation
 */
export class GitLabProvider extends BaseProvider {
  private client: plugins.gitlabClient.GitLabClient;

  constructor(connectionId: string, baseUrl: string, token: string) {
    super(connectionId, baseUrl, token);
    this.client = new plugins.gitlabClient.GitLabClient(baseUrl, token);
  }

  async testConnection(): Promise<ITestConnectionResult> {
    return this.client.testConnection();
  }

  async getProjects(opts?: IListOptions): Promise<interfaces.data.IProject[]> {
    const projects = await this.client.getProjects(opts);
    return projects.map((p) => this.mapProject(p));
  }

  async getGroups(opts?: IListOptions): Promise<interfaces.data.IGroup[]> {
    const groups = await this.client.getGroups(opts);
    return groups.map((g) => this.mapGroup(g));
  }

  // --- Project Secrets (CI/CD Variables) ---

  async getProjectSecrets(projectId: string): Promise<interfaces.data.ISecret[]> {
    const vars = await this.client.getProjectVariables(projectId);
    return vars.map((v) => this.mapVariable(v, 'project', projectId));
  }

  async createProjectSecret(
    projectId: string,
    key: string,
    value: string,
  ): Promise<interfaces.data.ISecret> {
    const v = await this.client.createProjectVariable(projectId, key, value);
    return this.mapVariable(v, 'project', projectId);
  }

  async updateProjectSecret(
    projectId: string,
    key: string,
    value: string,
  ): Promise<interfaces.data.ISecret> {
    const v = await this.client.updateProjectVariable(projectId, key, value);
    return this.mapVariable(v, 'project', projectId);
  }

  async deleteProjectSecret(projectId: string, key: string): Promise<void> {
    await this.client.deleteProjectVariable(projectId, key);
  }

  // --- Group Secrets (CI/CD Variables) ---

  async getGroupSecrets(groupId: string): Promise<interfaces.data.ISecret[]> {
    const vars = await this.client.getGroupVariables(groupId);
    return vars.map((v) => this.mapVariable(v, 'group', groupId));
  }

  async createGroupSecret(
    groupId: string,
    key: string,
    value: string,
  ): Promise<interfaces.data.ISecret> {
    const v = await this.client.createGroupVariable(groupId, key, value);
    return this.mapVariable(v, 'group', groupId);
  }

  async updateGroupSecret(
    groupId: string,
    key: string,
    value: string,
  ): Promise<interfaces.data.ISecret> {
    const v = await this.client.updateGroupVariable(groupId, key, value);
    return this.mapVariable(v, 'group', groupId);
  }

  async deleteGroupSecret(groupId: string, key: string): Promise<void> {
    await this.client.deleteGroupVariable(groupId, key);
  }

  // --- Pipelines ---

  async getPipelines(
    projectId: string,
    opts?: IListOptions,
  ): Promise<interfaces.data.IPipeline[]> {
    const pipelines = await this.client.getPipelines(projectId, opts);
    return pipelines.map((p) => this.mapPipeline(p, projectId));
  }

  async getPipelineJobs(
    projectId: string,
    pipelineId: string,
  ): Promise<interfaces.data.IPipelineJob[]> {
    const jobs = await this.client.getPipelineJobs(projectId, Number(pipelineId));
    return jobs.map((j) => this.mapJob(j, pipelineId));
  }

  async getJobLog(projectId: string, jobId: string): Promise<string> {
    return this.client.getJobLog(projectId, Number(jobId));
  }

  async retryPipeline(projectId: string, pipelineId: string): Promise<void> {
    await this.client.retryPipeline(projectId, Number(pipelineId));
  }

  async cancelPipeline(projectId: string, pipelineId: string): Promise<void> {
    await this.client.cancelPipeline(projectId, Number(pipelineId));
  }

  // --- Mappers ---

  private mapProject(p: plugins.gitlabClient.IGitLabProject): interfaces.data.IProject {
    return {
      id: String(p.id),
      name: p.name || '',
      fullPath: p.path_with_namespace || '',
      description: p.description || '',
      defaultBranch: p.default_branch || 'main',
      webUrl: p.web_url || '',
      connectionId: this.connectionId,
      visibility: p.visibility || 'private',
      topics: p.topics || [],
      lastActivity: p.last_activity_at || '',
    };
  }

  private mapGroup(g: plugins.gitlabClient.IGitLabGroup): interfaces.data.IGroup {
    return {
      id: String(g.id),
      name: g.name || '',
      fullPath: g.full_path || '',
      description: g.description || '',
      webUrl: g.web_url || '',
      connectionId: this.connectionId,
      visibility: g.visibility || 'private',
      projectCount: 0,
    };
  }

  private mapVariable(
    v: plugins.gitlabClient.IGitLabVariable,
    scope: 'project' | 'group',
    scopeId: string,
    scopeName?: string,
  ): interfaces.data.ISecret {
    return {
      key: v.key || '',
      value: v.value || '***',
      protected: v.protected || false,
      masked: v.masked || false,
      scope,
      scopeId,
      scopeName: scopeName || scopeId,
      connectionId: this.connectionId,
      environment: v.environment_scope || '*',
    };
  }

  private mapPipeline(p: plugins.gitlabClient.IGitLabPipeline, projectId: string): interfaces.data.IPipeline {
    return {
      id: String(p.id),
      projectId,
      projectName: projectId,
      connectionId: this.connectionId,
      status: (p.status || 'pending') as interfaces.data.TPipelineStatus,
      ref: p.ref || '',
      sha: p.sha || '',
      webUrl: p.web_url || '',
      duration: p.duration || 0,
      createdAt: p.created_at || '',
      source: p.source || 'push',
    };
  }

  private mapJob(j: plugins.gitlabClient.IGitLabJob, pipelineId: string): interfaces.data.IPipelineJob {
    return {
      id: String(j.id),
      pipelineId: String(pipelineId),
      name: j.name || '',
      stage: j.stage || '',
      status: (j.status || 'pending') as interfaces.data.TPipelineStatus,
      duration: j.duration || 0,
    };
  }
}
