package mocks

import (
	"strings"
	"time"

	"github.com/go-pg/pg/v10/orm"

	"github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/db/queries"
	"github.com/fiskerinc/cloud-services/pkg/validator"
)

type MockIssue struct {
	SelectIssuesResponse []common.Issue
	DBMockHelper
}

func (c *MockIssue) Insert(issue *common.Issue) (orm.Result, error) {
	return c.ORMResponse, c.Error
}

func (c *MockIssue) Delete(id int) (orm.Result, error) {
	if id <= 0 {
		return nil, &validator.FieldError{
			ErrorMsg: "id cannot be less than 0",
		}
	}
	return c.ORMResponse, c.Error
}

func (c *MockIssue) SelectByID(id int) (*common.Issue, error) {
	if id <= 0 {
		return nil, &validator.FieldError{
			ErrorMsg: "id cannot be less than 0",
		}
	}

	issueImage := []common.IssueImage{
		{
			ID:      1,
			Image:   []byte{},
			IssueID: 1,
		},
	}
	return &common.Issue{
		ID:          1,
		VIN:         "",
		Title:       "",
		Description: "",
		DriverID:    "",
		Timestamp:   time.Time{},
		IssueImages: issueImage,
	}, nil
}

func (c *MockIssue) Search(filter *common.IssueSearch, paging *queries.PageQueryOptions) ([]common.Issue, error) {
	if c.SelectIssuesResponse != nil {
		if filter.Search != "" && strings.Contains(c.SelectIssuesResponse[0].Title, filter.Search) {
			return []common.Issue{c.SelectIssuesResponse[0]}, nil
		}

		return c.SelectIssuesResponse, nil
	}

	return []common.Issue{
		{
			ID:          1,
			VIN:         "",
			Title:       "",
			Description: "",
			DriverID:    "",
			Timestamp:   time.Time{},
			IssueImages: []common.IssueImage{},
		},
	}, nil
}

func (c *MockIssue) Count() (int, error) {
	return 1, nil
}

func (c *MockIssue) SetListResp(list interface{}) {
	if list != nil {
		c.SelectIssuesResponse = list.([]common.Issue)
	} else {
		c.SelectIssuesResponse = nil
	}
}

type MockIssueImages struct {
	queries.QueryBase
	SearchByIssueIDResponse []common.IssueImage
	DBMockHelper
}

func (c *MockIssueImages) Insert(issueImage *[]common.IssueImage) (orm.Result, error) {
	return c.ORMResponse, c.Error
}

func (c *MockIssueImages) SearchByIssueID(issueID string) ([]common.IssueImage, error) {
	return []common.IssueImage{
		{
			ID:      1,
			Image:   []byte{0, 1, 0},
			IssueID: 1,
		},
	}, nil
}
