package controller

import (
	"context"
	"errors"
	"fmt"
	"log"
	"ticket-pimp/internal/domain"
	"ticket-pimp/internal/storage/db"
	"time"

	"github.com/jackc/pgx/v5/pgtype"
)

type FolderRequest struct {
	ChannelID    string
	InsertedName string
}

func (wc *WorkflowController) CreateFolder(ctx context.Context, req FolderRequest) *ProjectResponse {

	project, err := wc.GetProjectByChannelID(ctx, req.ChannelID)
	if err != nil {
		return &ProjectResponse{
			Project: nil,
			Message: fmt.Errorf("unable to retrieve project from db: %v", err),
		}
	}

	var (
		name     string
		dbticket db.Ticket
		result   ProjectResponse
	)

	if project != nil {
		switch {
		case project.Folder != "":
			return &ProjectResponse{
				Project: project,
				Message: nil,
			}
		case project.Key != "":
			name = project.Key
		case req.InsertedName != "":
			name = req.InsertedName
		}
		response := wc.ICloud.CreateFolder(name)

		dbticket, err = wc.q.UpdateTicketFolder(
			ctx,
			db.UpdateTicketFolderParams{
				Folder:    pgtype.Text{String: response.Folder.PrivateURL, Valid: true},
				UpdatedAt: pgtype.Timestamptz{Time: time.Now(), InfinityModifier: 0, Valid: true},
				Channelid: pgtype.Text{String: req.ChannelID, Valid: true},
			})
		if err != nil {
			log.Printf("unable to scan row from db: %v", err)
			return &ProjectResponse{
				Project: project,
				Message: fmt.Errorf("unable to update project: %v", err),
			}
		}

		result = ProjectResponse{
			Project: &domain.Project{
				ID:         string(dbticket.ID),
				Name:       dbticket.Title.String,
				Key:        dbticket.Key.String,
				ChannelID:  dbticket.Channelid.String,
				ProjectGit: dbticket.ProjectGit.String,
				BuildGit:   dbticket.BuildGit.String,
				Folder:     dbticket.Folder.String,
			},
			Message: response.ErrMessage,
		}
	} else {
		if req.InsertedName != "" {
			response := wc.ICloud.CreateFolder(req.InsertedName)
			result = ProjectResponse{
				Project: &domain.Project{
					Folder: response.Folder.PrivateURL,
				},
				Message: response.ErrMessage,
			}
		} else {
			return &ProjectResponse{
				Project: nil,
				Message: errors.New("передано пустое имя"),
			}
		}
	}

	return &result
}
