// Copyright 2016 The go-github AUTHORS. All rights reserved.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package github

import (
	"context"
	"errors"
	"fmt"
)

// MigrationService provides access to the migration related functions
// in the GitHub API.
//
// GitHub API docs: https://docs.github.com/rest/migrations?apiVersion=2022-11-28
type MigrationService service

// Migration represents a GitHub migration (archival).
type Migration struct {
	ID   *int64  `json:"id,omitempty"`
	GUID *string `json:"guid,omitempty"`
	// State is the current state of a migration.
	// Possible values are:
	//     "pending" which means the migration hasn't started yet,
	//     "exporting" which means the migration is in progress,
	//     "exported" which means the migration finished successfully, or
	//     "failed" which means the migration failed.
	State *string `json:"state,omitempty"`
	// LockRepositories indicates whether repositories are locked (to prevent
	// manipulation) while migrating data.
	LockRepositories *bool `json:"lock_repositories,omitempty"`
	// ExcludeAttachments indicates whether attachments should be excluded from
	// the migration (to reduce migration archive file size).
	ExcludeAttachments *bool         `json:"exclude_attachments,omitempty"`
	URL                *string       `json:"url,omitempty"`
	CreatedAt          *string       `json:"created_at,omitempty"`
	UpdatedAt          *string       `json:"updated_at,omitempty"`
	Repositories       []*Repository `json:"repositories,omitempty"`
}

func (m Migration) String() string {
	return Stringify(m)
}

// MigrationOptions specifies the optional parameters to Migration methods.
type MigrationOptions struct {
	// LockRepositories indicates whether repositories should be locked (to prevent
	// manipulation) while migrating data.
	LockRepositories bool

	// ExcludeAttachments indicates whether attachments should be excluded from
	// the migration (to reduce migration archive file size).
	ExcludeAttachments bool

	// ExcludeReleases indicates whether releases should be excluded from
	// the migration (to reduce migration archive file size).
	ExcludeReleases bool

	// Exclude is a slice of related items to exclude from the response in order
	// to improve performance of the request. Supported values are: "repositories"
	Exclude []string
}

// startMigration represents the body of a StartMigration request.
type startMigration struct {
	// Repositories is a slice of repository names to migrate.
	Repositories []string `json:"repositories,omitempty"`

	// LockRepositories indicates whether repositories should be locked (to prevent
	// manipulation) while migrating data.
	LockRepositories *bool `json:"lock_repositories,omitempty"`

	// ExcludeAttachments indicates whether attachments should be excluded from
	// the migration (to reduce migration archive file size).
	ExcludeAttachments *bool `json:"exclude_attachments,omitempty"`

	// ExcludeReleases indicates whether releases should be excluded from
	// the migration (to reduce migration archive file size).
	ExcludeReleases *bool `json:"exclude_releases,omitempty"`

	// Exclude is a slice of related items to exclude from the response in order
	// to improve performance of the request. Supported values are: "repositories"
	Exclude []string `json:"exclude,omitempty"`
}

// StartMigration starts the generation of a migration archive.
// repos is a slice of repository names to migrate.
//
// GitHub API docs: https://docs.github.com/rest/migrations/orgs?apiVersion=2022-11-28#start-an-organization-migration
//
//meta:operation POST /orgs/{org}/migrations
func (s *MigrationService) StartMigration(ctx context.Context, org string, repos []string, opts *MigrationOptions) (*Migration, *Response, error) {
	u := fmt.Sprintf("orgs/%v/migrations", org)

	body := &startMigration{Repositories: repos}
	if opts != nil {
		body.LockRepositories = &opts.LockRepositories
		body.ExcludeAttachments = &opts.ExcludeAttachments
		body.ExcludeReleases = &opts.ExcludeReleases
		body.Exclude = append(body.Exclude, opts.Exclude...)
	}

	req, err := s.client.NewRequest(ctx, "POST", u, body)
	if err != nil {
		return nil, nil, err
	}

	req.Header.Set("Accept", mediaTypeMigrationsPreview)

	var m *Migration
	resp, err := s.client.Do(req, &m)
	if err != nil {
		return nil, resp, err
	}

	return m, resp, nil
}

// ListMigrations lists the most recent migrations.
//
// GitHub API docs: https://docs.github.com/rest/migrations/orgs?apiVersion=2022-11-28#list-organization-migrations
//
//meta:operation GET /orgs/{org}/migrations
func (s *MigrationService) ListMigrations(ctx context.Context, org string, opts *ListOptions) ([]*Migration, *Response, error) {
	u := fmt.Sprintf("orgs/%v/migrations", org)
	u, err := addOptions(u, opts)
	if err != nil {
		return nil, nil, err
	}

	req, err := s.client.NewRequest(ctx, "GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	req.Header.Set("Accept", mediaTypeMigrationsPreview)

	var m []*Migration
	resp, err := s.client.Do(req, &m)
	if err != nil {
		return nil, resp, err
	}

	return m, resp, nil
}

// MigrationStatus gets the status of a specific migration archive.
// id is the migration ID.
//
// GitHub API docs: https://docs.github.com/rest/migrations/orgs?apiVersion=2022-11-28#get-an-organization-migration-status
//
//meta:operation GET /orgs/{org}/migrations/{migration_id}
func (s *MigrationService) MigrationStatus(ctx context.Context, org string, id int64) (*Migration, *Response, error) {
	u := fmt.Sprintf("orgs/%v/migrations/%v", org, id)

	req, err := s.client.NewRequest(ctx, "GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	req.Header.Set("Accept", mediaTypeMigrationsPreview)

	var m *Migration
	resp, err := s.client.Do(req, &m)
	if err != nil {
		return nil, resp, err
	}

	return m, resp, nil
}

// MigrationArchiveURL fetches a migration archive URL.
// id is the migration ID.
//
// GitHub API docs: https://docs.github.com/rest/migrations/orgs?apiVersion=2022-11-28#download-an-organization-migration-archive
//
//meta:operation GET /orgs/{org}/migrations/{migration_id}/archive
func (s *MigrationService) MigrationArchiveURL(ctx context.Context, org string, id int64) (url string, err error) {
	u := fmt.Sprintf("orgs/%v/migrations/%v/archive", org, id)

	req, err := s.client.NewRequest(ctx, "GET", u, nil)
	if err != nil {
		return "", err
	}
	req.Header.Set("Accept", mediaTypeMigrationsPreview)

	loc, _, err := s.client.bareDoUntilFound(req, 10)
	if err != nil {
		return "", err
	}

	if loc == nil {
		return "", errors.New("expected redirect, none provided")
	}

	return loc.String(), nil
}

// DeleteMigration deletes a previous migration archive.
// id is the migration ID.
//
// GitHub API docs: https://docs.github.com/rest/migrations/orgs?apiVersion=2022-11-28#delete-an-organization-migration-archive
//
//meta:operation DELETE /orgs/{org}/migrations/{migration_id}/archive
func (s *MigrationService) DeleteMigration(ctx context.Context, org string, id int64) (*Response, error) {
	u := fmt.Sprintf("orgs/%v/migrations/%v/archive", org, id)

	req, err := s.client.NewRequest(ctx, "DELETE", u, nil)
	if err != nil {
		return nil, err
	}

	req.Header.Set("Accept", mediaTypeMigrationsPreview)

	return s.client.Do(req, nil)
}

// UnlockRepo unlocks a repository that was locked for migration.
// id is the migration ID.
// You should unlock each migrated repository and delete them when the migration
// is complete and you no longer need the source data.
//
// GitHub API docs: https://docs.github.com/rest/migrations/orgs?apiVersion=2022-11-28#unlock-an-organization-repository
//
//meta:operation DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock
func (s *MigrationService) UnlockRepo(ctx context.Context, org string, id int64, repo string) (*Response, error) {
	u := fmt.Sprintf("orgs/%v/migrations/%v/repos/%v/lock", org, id, repo)

	req, err := s.client.NewRequest(ctx, "DELETE", u, nil)
	if err != nil {
		return nil, err
	}

	req.Header.Set("Accept", mediaTypeMigrationsPreview)

	return s.client.Do(req, nil)
}
