package social

import (
	"context"
	"fmt"
	"slices"

	"github.com/google/uuid"

	"scrabble/backend/internal/notify"
)

// RobotBlock is one per-game block of a disguised-robot opponent: the row id (used to
// unblock it), the game name the player saw, and the game + seat it was blocked in.
type RobotBlock struct {
	ID          uuid.UUID
	DisplayName string
	GameID      uuid.UUID
	Seat        int
}

// BlockInGame blocks blockedID for blockerID from within gameID. A human is blocked
// normally (the blocks table, via Block). A disguised-robot opponent is instead recorded
// per-game in robot_blocks — never the shared robot account — so the matchmaker keeps
// robots free and the same robot stays unblocked in the blocker's other games (under its
// other names); the row snapshots the seat and the name the player saw so the blocked list
// and the in-game card can show it. It is the entry point for the in-game block control;
// the settings-screen block (no game) goes through Block directly.
func (svc *Service) BlockInGame(ctx context.Context, blockerID, blockedID, gameID uuid.UUID) error {
	if blockerID == blockedID {
		return ErrSelfRelation
	}
	isRobot, err := svc.accounts.IsRobot(ctx, blockedID)
	if err != nil {
		return err
	}
	if !isRobot {
		return svc.Block(ctx, blockerID, blockedID)
	}
	if gameID == uuid.Nil {
		return ErrNotParticipant
	}
	seats, _, _, err := svc.games.Participants(ctx, gameID)
	if err != nil {
		return err
	}
	seat := slices.Index(seats, blockedID)
	if seat < 0 {
		return ErrNotParticipant
	}
	name, _ := svc.games.SeatName(ctx, gameID, blockedID)
	if err := svc.store.insertRobotBlock(ctx, blockerID, gameID, seat, blockedID, name); err != nil {
		return err
	}
	svc.pub.Publish(notify.NotificationAccount(blockerID, notify.NotifyUserBlocked, svc.accountRef(ctx, blockedID)))
	return nil
}

// ListRobotBlocks returns blockerID's per-game disguised-robot blocks, newest first.
func (svc *Service) ListRobotBlocks(ctx context.Context, blockerID uuid.UUID) ([]RobotBlock, error) {
	return svc.store.listRobotBlocks(ctx, blockerID)
}

// insertRobotBlock records a per-game robot block; a duplicate (same blocker, game, seat)
// is ignored.
func (s *Store) insertRobotBlock(ctx context.Context, blocker, gameID uuid.UUID, seat int, robotID uuid.UUID, name string) error {
	id, err := uuid.NewV7()
	if err != nil {
		return fmt.Errorf("social: new robot block id: %w", err)
	}
	const q = `INSERT INTO backend.robot_blocks (id, blocker_id, game_id, seat, robot_id, display_name)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (blocker_id, game_id, seat) DO NOTHING`
	if _, err := s.db.ExecContext(ctx, q, id, blocker, gameID, int16(seat), robotID, name); err != nil {
		return fmt.Errorf("social: insert robot block: %w", err)
	}
	return nil
}

// deleteRobotBlock removes blocker's robot block by its row id, reporting whether a row
// matched (so the caller can fall back to a human block).
func (s *Store) deleteRobotBlock(ctx context.Context, blocker, id uuid.UUID) (bool, error) {
	const q = `DELETE FROM backend.robot_blocks WHERE id = $2 AND blocker_id = $1`
	res, err := s.db.ExecContext(ctx, q, blocker, id)
	if err != nil {
		return false, fmt.Errorf("social: delete robot block: %w", err)
	}
	n, err := res.RowsAffected()
	if err != nil {
		return false, fmt.Errorf("social: delete robot block rows: %w", err)
	}
	return n > 0, nil
}

// listRobotBlocks returns blocker's robot blocks, newest first.
func (s *Store) listRobotBlocks(ctx context.Context, blocker uuid.UUID) ([]RobotBlock, error) {
	const q = `SELECT id, display_name, game_id, seat FROM backend.robot_blocks
WHERE blocker_id = $1 ORDER BY created_at DESC`
	rows, err := s.db.QueryContext(ctx, q, blocker)
	if err != nil {
		return nil, fmt.Errorf("social: list robot blocks: %w", err)
	}
	defer rows.Close()
	var out []RobotBlock
	for rows.Next() {
		var rb RobotBlock
		var seat int16
		if err := rows.Scan(&rb.ID, &rb.DisplayName, &rb.GameID, &seat); err != nil {
			return nil, fmt.Errorf("social: scan robot block: %w", err)
		}
		rb.Seat = int(seat)
		out = append(out, rb)
	}
	return out, rows.Err()
}
